### Install MCP Server Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md Instructions for installing the MCP server using pip or npm. ```bash pip install mcp-server-fetch # or npm install -g @modelcontextprotocol/server-something ``` -------------------------------- ### Development Setup - Installation Source: https://github.com/adhikasp/mcp-client-cli/blob/master/AGENTS.md Steps to clone the repository, create a virtual environment, and install the project in editable mode using uv. ```bash # Clone the repository git clone https://github.com/adhikasp/mcp-client-cli.git cd mcp-client-cli # Create virtual environment and install in editable mode uv venv source .venv/bin/activate # Linux/macOS # .venv\Scripts\activate # Windows uv pip install -e . ``` -------------------------------- ### OutputHandler start() and finish() Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/output.md Shows the basic lifecycle of starting and finishing the output display. ```python output = OutputHandler() output.start() # Update with data... output.finish() ``` -------------------------------- ### Tool Loading Error Recovery Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/errors.md Examples of commands to test if a server is available and how to install it if it's not. ```bash # Test if server is available uvx mcp-server-fetch --help # If not installed, install it pip install mcp-server-fetch # or uvx pip install mcp-server-fetch ``` -------------------------------- ### OutputHandler stop() and start() Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/output.md Shows how to temporarily stop and then resume the live output display. ```python output = OutputHandler() output.start() # Update output... output.stop() # Stop display, prepare for tool confirmation output.start() # Resume display ``` -------------------------------- ### Basic Usage Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/README.md Example of a simple query and its response. ```bash $ llm What is the capital city of North Sumatra? The capital city of North Sumatra is Medan. ``` -------------------------------- ### OutputHandler finish() Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/output.md A more complete example showing the start, update, and finish sequence for output handling. ```python output = OutputHandler() output.start() # Update output... output.finish() # Display final result ``` -------------------------------- ### setup_argument_parser() usage example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/cli.md Example of how to use the setup_argument_parser() and access its arguments. ```python # Invokes parser and returns parsed arguments args = setup_argument_parser() # Access arguments if args.list_tools: # Handle --list-tools pass if args.model: # Override model override_model = args.model ``` -------------------------------- ### Environment Variables Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/configuration.md Example of setting environment variables for API keys and server-specific configurations. ```bash export LLM_API_KEY="sk-proj-..." export BRAVE_API_KEY="your-brave-api-key" llm "Search for Python best practices" ``` -------------------------------- ### Cache key format example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/constants.md Examples illustrating the cache key format. ```text uvx-mcp-server-fetch → "uvx-mcp-server-fetch.json" npx--y-@modelcontextprotocol/server-brave-search → "npx--y-@modelcontextprotocol-server-brave-search.json" ``` -------------------------------- ### ServerConfig from_dict Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/config.md Example of creating a ServerConfig object from a dictionary. ```python server_dict = { "command": "uvx", "args": ["mcp-server-fetch"], "enabled": True, "exclude_tools": ["read_file"], "requires_confirmation": ["delete_file"] } server_config = ServerConfig.from_dict(server_dict) ``` -------------------------------- ### Configuration file example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/README.md Example JSON configuration for LLM and MCP servers. ```json { "systemPrompt": "You are an AI assistant helping a software engineer...", "llm": { "provider": "openai", "model": "gpt-4", "api_key": "your-openai-api-key", "temperature": 0.7, "base_url": "https://api.openai.com/v1" // Optional, for OpenRouter or other providers }, "mcpServers": { "fetch": { "command": "uvx", "args": ["mcp-server-fetch"], "requires_confirmation": ["fetch"], "enabled": true, // Optional, defaults to true "exclude_tools": [] // Optional, list of tool names to exclude }, "brave-search": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-brave-search"], "env": { "BRAVE_API_KEY": "your-brave-api-key" }, "requires_confirmation": ["brave_web_search"] }, "youtube": { "command": "uvx", "args": ["--from", "git+https://github.com/adhikasp/mcp-youtube", "mcp-youtube"] } } } ``` -------------------------------- ### Start Initial Conversation Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md Initiating a new conversation thread. ```bash $ llm "What are the benefits of Python?" Python offers several benefits... ``` -------------------------------- ### Usage Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md Example of how to run the `run_custom_agent` function and print its result. ```python # Usage import asyncio result = asyncio.run(run_custom_agent("What is Python?")) print(result) ``` -------------------------------- ### AppConfig.load() Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/config.md Example demonstrating how to load and access configuration using AppConfig.load(). ```python from mcp_client_cli.config import AppConfig # Load configuration from file config = AppConfig.load() # Access LLM configuration print(config.llm.model) print(config.llm.provider) # Access enabled servers enabled_servers = config.get_enabled_servers() for server_name, server_config in enabled_servers.items(): print(f"Server: {server_name}") ``` -------------------------------- ### LLMConfig.from_dict() Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/config.md Example of creating an LLMConfig instance from a dictionary. ```python config_dict = { "provider": "openai", "model": "gpt-4-turbo", "temperature": 0.7 } llm_config = LLMConfig.from_dict(config_dict) ``` -------------------------------- ### SqliteStore Constructor Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/storage.md Examples of initializing SqliteStore, both without and with vector search configuration. ```python from mcp_client_cli.storage import SqliteStore # Basic store without vector search store = SqliteStore("~/.llm/conversations.db") # With vector search from langgraph.store.base import IndexConfig index_config = IndexConfig(fields=["$"], embed="text-embedding-3-small") store = SqliteStore("~/.llm/conversations.db", index=index_config) ``` -------------------------------- ### Example Top-Level Configuration Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/configuration.md A complete example of the top-level configuration file, demonstrating system prompt, LLM settings, and multiple MCP server configurations. ```json { "systemPrompt": "You are an AI assistant helping a software engineer with coding tasks.", "llm": { "provider": "openai", "model": "gpt-4o", "api_key": "sk-...", "temperature": 0, "base_url": "https://api.openai.com/v1" }, "mcpServers": { "fetch": { "command": "uvx", "args": ["mcp-server-fetch"], "enabled": true }, "brave-search": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-brave-search"], "env": { "BRAVE_API_KEY": "your-api-key" }, "requires_confirmation": ["brave_web_search"] } } } ``` -------------------------------- ### Simple Question Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md A basic query to the LLM. ```bash llm "What is the capital of France?" ``` -------------------------------- ### handle_list_tools() example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/cli.md Example of invoking the --list-tools command and its output. ```bash $ llm --list-tools Available LLM Tools ┌───────────┬──────────────┬─────────────────────┐ │ Toolkit │ Tool Name │ Description │ ├───────────┼──────────────┼─────────────────────┤ │ fetch │ fetch │ Fetch web content │ │ brave │ brave_search │ Search with Brave │ └───────────┴──────────────┴─────────────────────┘ ``` -------------------------------- ### Example Configuration Source: https://github.com/adhikasp/mcp-client-cli/blob/master/CONFIG.md An example of a complete MCP Client CLI configuration file. ```json { "systemPrompt": "You are an AI assistant helping a software engineer...", "llm": { "provider": "openai", "model": "gpt-4o-mini", "api_key": "your-api-key-here", "temperature": 0 }, "mcpServers": { "fetch": { "command": "uvx", "args": ["mcp-server-fetch"] }, "brave-search": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-brave-search"], "env": { "BRAVE_API_KEY": "your-brave-api-key-here" } }, "mcp-server-commands": { "command": "npx", "args": ["mcp-server-commands"], "requires_confirmation": [ "run_command", "run_script" ] } } } ``` -------------------------------- ### Complete Configuration Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/configuration.md A comprehensive example of the MCP Client CLI configuration file, including system prompt, LLM settings, and various MCP server configurations. ```json { "systemPrompt": "You are an expert software engineer and technical writer. Help the user with coding, debugging, and documentation. Be concise and practical.", "llm": { "provider": "openai", "model": "gpt-4o", "api_key": "sk-proj-...", "temperature": 0, "base_url": null }, "mcpServers": { "fetch": { "command": "uvx", "args": ["mcp-server-fetch"], "enabled": true, "exclude_tools": [], "requires_confirmation": [] }, "brave-search": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-brave-search"], "env": { "BRAVE_API_KEY": "your-brave-api-key" }, "enabled": true, "exclude_tools": [], "requires_confirmation": ["brave_web_search"] }, "commands": { "command": "npx", "args": ["mcp-server-commands"], "enabled": true, "exclude_tools": [], "requires_confirmation": ["run_command", "run_shell_command"] }, "git": { "command": "npx", "args": ["mcp-server-git"], "enabled": true, "exclude_tools": [], "requires_confirmation": ["git_push"] }, "youtube": { "command": "uvx", "args": ["--from", "git+https://github.com/adhikasp/mcp-youtube", "mcp-youtube"], "enabled": false, "env": {}, "exclude_tools": [], "requires_confirmation": [] } } } ``` -------------------------------- ### Standard input examples Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/input.md Examples demonstrating how to pipe image files or text files into the CLI for processing. ```bash $ cat image.jpg | llm "Describe this image" $ echo "Some text" | llm "Process this" ``` -------------------------------- ### Configuration with Comments Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/configuration.md An example of a configuration file that uses JSON comments for better readability. ```json { // System prompt for the LLM "systemPrompt": "You are a helpful AI assistant.", // LLM configuration "llm": { "provider": "openai", "model": "gpt-4o", // API key can also be set via LLM_API_KEY environment variable "api_key": "sk-...", "temperature": 0 }, // MCP servers "mcpServers": { // Web fetching and searching "fetch": { "command": "uvx", "args": ["mcp-server-fetch"] }, // Search the web "brave-search": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-brave-search"], "env": { "BRAVE_API_KEY": "your-brave-api-key" }, // Require confirmation before searching "requires_confirmation": ["brave_web_search"] } } } ``` -------------------------------- ### Get tools Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md Python code to retrieve the list of tools generated from the MCP server configuration. ```python # Get tools tools = toolkit.get_tools() print(f"Loaded {len(tools)} tools") ``` -------------------------------- ### Model Selection for Queries Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md Examples of selecting different models for simple versus complex queries to optimize performance and cost. ```bash # Use faster, cheaper model for simple queries llm --model gpt-3.5-turbo "Simple question" # Use advanced model for complex analysis llm --model gpt-4 "Complex multi-step analysis" ``` -------------------------------- ### Multi-Step Reasoning Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md Shows how a single query can trigger a chain of tool executions for complex tasks like searching, fetching, and summarizing. ```bash # Agent can chain multiple tools together llm "Search for latest Python docs, fetch details, summarize" # Single query triggers: # 1. Search tool # 2. Fetch tool # 3. Summarization ``` -------------------------------- ### List Available Tools Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md Listing all available tools managed by MCP. ```bash $ llm --list-tools Available LLM Tools ┌───────────────┬──────────────────┬─────────────────────┐ │ Toolkit │ Tool Name │ Description │ ├───────────────┼──────────────────┼─────────────────────┤ │ fetch │ fetch │ Fetch web content │ │ brave-search │ brave_web_search │ Search the web │ │ commands │ run_command │ Execute shell cmd │ │ git │ git_diff │ Show git changes │ └───────────────┴──────────────────┴─────────────────────┘ ``` -------------------------------- ### Requires Confirmation Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/configuration.md An example showing how to specify tools that require user confirmation before execution. ```json "requires_confirmation": ["delete_file", "execute_command"] ``` -------------------------------- ### Triggering a tool example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/README.md Example of triggering a tool (brave-search) and subsequent tool (fetch). ```bash $ llm What is the top article on hackernews today? ================================== Ai Message ================================== Tool Calls: brave_web_search (call_eXmFQizLUp8TKBgPtgFo71et) Call ID: call_eXmFQizLUp8TKBgPtgFo71et Args: query: site:news.ycombinator.com count: 1 Brave Search MCP Server running on stdio # If the tool requires confirmation, you'll be prompted: Confirm tool call? [y/n]: y ================================== Ai Message ================================== Tool Calls: fetch (call_xH32S0QKqMfudgN1ZGV6vH1P) Call ID: call_xH32S0QKqMfudgN1ZGV6vH1P Args: url: https://news.ycombinator.com/ ================================= Tool Message ================================= Name: fetch [TextContent(type='text', text='Contents [REDACTED]] ================================== Ai Message ================================== The top article on Hacker News today is: ``` -------------------------------- ### CI/CD Pipeline for AI Code Review Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md A GitHub Actions workflow that checks out code, installs the CLI, reviews changes using llm, and posts the review. ```yaml # .github/workflows/code-review.yml name: AI Code Review on: [pull_request] jobs: review: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 - name: Install CLI run: pip install mcp-client-cli - name: Review Changes run: | git diff HEAD^ | llm --text-only "Review these changes" \ > review.txt - name: Post Review run: cat review.txt ``` -------------------------------- ### AppConfig.get_enabled_servers() Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/config.md Example showing how to use get_enabled_servers() to filter for enabled servers. ```python config = AppConfig.load() enabled = config.get_enabled_servers() # Only contains servers where enabled=true in config for name, server_config in enabled.items(): print(f"{name}: {server_config.command}") ``` -------------------------------- ### LLM Temperature Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/configuration.md Example JSON snippet for setting the LLM temperature. ```json "temperature": 0.5 ``` -------------------------------- ### AgentState Usage Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/cli.md Example demonstrating how to instantiate and use the AgentState TypedDict for the ReAct agent. ```python from mcp_client_cli.cli import AgentState from langchain_core.messages import HumanMessage state = AgentState( messages=[HumanMessage(content="Hi")], today_datetime="2024-01-01T12:00:00", memories="- User prefers concise responses", remaining_steps=3 ) ``` -------------------------------- ### save_tools_cache Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/storage.md Example of how to save tools to the cache. ```python from mcp_client_cli.storage import save_tools_cache from mcp import StdioServerParameters, types server_param = StdioServerParameters( command="uvx", args=["mcp-server-fetch"] ) # Assuming tools is List[types.Tool] from MCP server save_tools_cache(server_param, tools) ``` -------------------------------- ### Prompt template usage examples Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/input.md Examples of how to use prompt templates with the `p` prefix for specific tasks like reviewing git changes, generating commit messages, or summarizing YouTube videos. ```bash $ llm p review # Review git changes $ llm p commit # Generate commit message $ llm p yt url=https://... # Summarize video ``` -------------------------------- ### LLM Provider Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/configuration.md Example JSON snippet for setting the LLM provider. ```json "provider": "openai" ``` -------------------------------- ### Usage of CONFIG_DIR Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/constants.md Example demonstrating how to construct a configuration path using CONFIG_DIR. ```python from mcp_client_cli.const import CONFIG_DIR config_path = CONFIG_DIR / "config.json" # Points to: ~/.llm/config.json ``` -------------------------------- ### SqliteStore abatch() Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/storage.md Example demonstrating the use of abatch() with a list of PutOp and SearchOp operations. ```python from langgraph.store.base import GetOp, PutOp, SearchOp store = SqliteStore(db_path, index=index_config) ops = [ PutOp( namespace=("memories", "user1"), key="mem_123", value={"data": "important fact"} ), SearchOp( namespace_prefix=("memories",), query="important", limit=10 ) ] results = await store.abatch(ops) ``` -------------------------------- ### get_cached_tools Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/storage.md Example of how to retrieve cached tools if available and not expired. ```python from mcp_client_cli.storage import get_cached_tools from mcp import StdioServerParameters server_param = StdioServerParameters( command="uvx", args=["mcp-server-fetch"] ) cached = get_cached_tools(server_param) if cached: print(f"Found {len(cached)} cached tools") else: print("Cache expired or missing") ``` -------------------------------- ### handle_list_prompts() example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/cli.md Example of invoking the --list-prompts command and its output. ```bash $ llm --list-prompts Available Prompt Templates ┌────────┬──────────┬──────────────┐ │ Name │ Template │ Arguments │ ├────────┼──────────┼──────────────┤ │ review │ You are… │ │ │ commit │ You are… │ │ │ yt │ Retell… │ url │ └────────┴──────────┴──────────────┘ ``` -------------------------------- ### Memory-Driven Responses Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md Demonstrates how the agent learns user preferences (like JSON output) and applies them in subsequent responses. ```bash # Ask question, agent saves relevant memories llm "I prefer JSON output format" # Agent learns and applies in future responses llm "Generate example code for sorting" # Uses memory: "User prefers JSON output format" ``` -------------------------------- ### LLM API Key Example (Environment Variables) Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/configuration.md Example bash commands for setting the LLM API key via environment variables. ```bash export LLM_API_KEY="sk-..." export OPENAI_API_KEY="sk-..." ``` -------------------------------- ### LLM Model Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/configuration.md Example JSON snippet for specifying the LLM model. ```json "model": "gpt-4-turbo" ``` -------------------------------- ### Use a Prompt Template Source: https://github.com/adhikasp/mcp-client-cli/blob/master/README.md Examples of using predefined prompt templates. ```bash llm p review # Review git changes ``` ```bash llm p commit # Generate commit message ``` ```bash llm p yt url=https://youtube.com/... # Summarize YouTube video ``` -------------------------------- ### ConversationManager Constructor Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/storage.md Example of initializing the ConversationManager with a specified database path. ```python from pathlib import Path from mcp_client_cli.storage import ConversationManager db_path = Path.home() / ".llm" / "conversations.db" manager = ConversationManager(db_path) ``` -------------------------------- ### Continuation message example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/input.md Example demonstrating how to continue a previous conversation using the `c` prefix. ```bash $ llm "What is the capital of France?" Paris $ llm c "Tell me about its history" # Uses same conversation thread as first query ``` -------------------------------- ### handle_show_memories() example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/cli.md Example of invoking the --show-memories command and its output. ```bash $ llm --show-memories My LLM Memories ┌──────────────────────┐ │ User prefers JSON │ │ Timezone is UTC │ └──────────────────────┘ ``` -------------------------------- ### load_tools Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/cli.md Example demonstrating the usage of the load_tools function to load MCP tools and convert them to LangChain tools. ```python server_configs = [ McpServerConfig( server_name="fetch", server_param=params ) ] toolkits, tools = await load_tools(server_configs, no_tools=False, force_refresh=False) # Use tools in agent # ... # Cleanup for toolkit in toolkits: await toolkit.close() ``` -------------------------------- ### Custom Checkpointing Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/architecture.md Demonstrates how to integrate a custom checkpointer with the LangGraph agent. ```python async with CustomCheckpointer(...) as checkpointer: agent = create_react_agent( model, tools, checkpointer=checkpointer ) ``` -------------------------------- ### Clipboard input examples Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/input.md Examples showing how to use the `cb` prefix with the CLI to process text or images from the clipboard, including continuing a conversation. ```bash # Text from clipboard $ llm cb "What language is this?" # Image from clipboard $ llm cb "What do you see?" # Clipboard with continuation $ llm cb c "Tell me more" ``` -------------------------------- ### Cache file format example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/constants.md Example JSON structure for cache file format. ```json { "cached_at": "2024-01-01T12:00:00.123456", "tools": [ { "name": "fetch", "description": "Fetch web content", "inputSchema": {...} } ] } ``` -------------------------------- ### MCP Server Arguments Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/configuration.md Example JSON snippet for specifying arguments for an MCP server command. ```json "args": ["mcp-server-fetch"] ``` -------------------------------- ### LLM API Key Example (JSON) Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/configuration.md Example JSON snippet for providing the LLM API key. ```json "api_key": "sk-..." ``` -------------------------------- ### McpToolkit.initialize Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/tool.md Example usage of the initialize method for McpToolkit, showing both cached and forced refresh initialization. ```python toolkit = McpToolkit( name="fetch", server_param=server_param, exclude_tools=[] ) # Initialize with cached tools await toolkit.initialize() # Force refresh from server await toolkit.initialize(force_refresh=True) ``` -------------------------------- ### MCP Server Arguments Example (npm) Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/configuration.md Example JSON snippet for specifying arguments for an npm-based MCP server command. ```json "args": ["-y", "@modelcontextprotocol/server-brave-search"] ``` -------------------------------- ### Review Git Changes Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md Using a template to review git changes. ```bash $ cd /path/to/git/repo $ llm p review # Agent will: # 1. Get current git status # 2. Get git diff # 3. Review changes # 4. Provide feedback ``` -------------------------------- ### Tool Filtering Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/architecture.md Illustrates dynamic filtering of tools before passing them to the agent. ```python filtered_tools = [ t for t in tools if not t.name.startswith('delete_') ] agent = create_react_agent(model, filtered_tools) ``` -------------------------------- ### Summarize YouTube Video Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md Using a template to summarize a YouTube video. ```bash $ llm p yt url=https://www.youtube.com/watch?v=abc123xyz # Agent will: # 1. Fetch video transcript or details # 2. Summarize concisely # 3. Use bullet points and markdown ``` -------------------------------- ### Piping Input from File Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/README.md Demonstrates piping input to the CLI from a file. ```bash $ echo "Given a location, tell me its capital city." > instructions.txt $ cat instruction.txt | llm "West Java" The capital city of West Java is Bandung. ``` -------------------------------- ### run() internal call example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/cli.md Example of how the run() function is called internally. ```python await run() ``` -------------------------------- ### handle_conversation Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/cli.md Example of how to call the handle_conversation function to manage the main conversation flow. ```python # Internal function, called by run() query = HumanMessage(content="What is the capital of France?") await handle_conversation(args, query, False, app_config) ``` -------------------------------- ### Usage of CONFIG_FILE Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/constants.md Example showing how to check for the existence of the CONFIG_FILE in the current directory. ```python from mcp_client_cli.const import CONFIG_FILE # Check if config exists in current directory import os if os.path.exists(CONFIG_FILE): print("Found config in current directory") ``` -------------------------------- ### Server-Specific Configuration Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md A JSON configuration snippet detailing settings for a specific MCP server named 'secure-server'. It includes the command to run the server, environment variables, confirmation requirements for certain actions, and tools to exclude. ```json { "mcpServers": { "secure-server": { "command": "npx", "args": ["mcp-server-something"], "env": { "API_KEY": "secret" }, "requires_confirmation": ["delete", "modify"], "exclude_tools": ["dangerous_operation"] } } } ``` -------------------------------- ### FileNotFoundError Recovery Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/errors.md Example of how to recover from a FileNotFoundError by creating a configuration file and retrying the command. ```bash # Create config file mkdir -p ~/.llm cat > ~/.llm/config.json << 'EOF' { "systemPrompt": "You are a helpful assistant.", "mcpServers": {} } EOF # Retry command llm "Hello" ``` -------------------------------- ### Piping Input Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/README.md Demonstrates piping input to the CLI from echo. ```bash $ echo "What is the capital city of North Sumatra?" | llm The capital city of North Sumatra is Medan. ``` -------------------------------- ### Raw Text Output Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md Getting raw text output without markdown formatting. ```bash # No markdown formatting, just raw text llm --text-only "Hello" # Useful for: # - Scripts that parse output # - Piping to other commands # - Simple text processing ``` -------------------------------- ### LLM Base URL Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/configuration.md Example JSON snippet for configuring a custom LLM base URL. ```json "base_url": "https://openrouter.ai/api/v1" ``` -------------------------------- ### Text Input from File Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md Processing text content from files. ```bash # Read file content and process cat source_code.py | llm "Review this code for security issues" # Combine file content with question cat README.md | llm "Summarize the main points" ``` -------------------------------- ### Complex Query with Images Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md Piping image data to the LLM for analysis. ```bash # Pipe image from file cat screenshot.png | llm "What error is shown in this screenshot?" # Detect image type automatically and encode as base64 cat diagram.jpg | llm "Explain what this architecture diagram shows" ``` -------------------------------- ### main() invocation example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/cli.md Example of how the main function is invoked via a shell command. ```bash $ llm "What is the capital of France?" ``` -------------------------------- ### McpServerConfig Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/tool.md Example usage of McpServerConfig to create a server configuration object. ```python from mcp import StdioServerParameters from mcp_client_cli.tool import McpServerConfig server_config = McpServerConfig( server_name="fetch", server_param=StdioServerParameters( command="uvx", args=["mcp-server-fetch"], env={} ), exclude_tools=["read_binary"] ) ``` -------------------------------- ### Image Input Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/README.md Demonstrates piping an image file to the CLI for analysis. ```bash $ cat image.jpg | llm "What do you see in this image?" [LLM will analyze and describe the image] ``` ```bash $ cat screenshot.png | llm "Is there any error in this screenshot?" [LLM will analyze the screenshot and point out any errors] ``` -------------------------------- ### Create agent (without tools for simplicity) Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md Python code to create a ReAct agent using Langgraph's `create_react_agent`. This example initializes the agent without any tools for simplicity. ```python # Create agent (without tools for simplicity) agent = create_react_agent(model, tools=[], prompt=prompt) ``` -------------------------------- ### Get conversation thread Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md Python code to retrieve the last conversation thread ID using the `ConversationManager`. ```python # Get conversation thread manager = ConversationManager(db_path) thread_id = await manager.get_last_id() print(f"Last conversation thread: {thread_id}") ``` -------------------------------- ### MCP Server Environment Variables Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/configuration.md Example JSON snippet for setting environment variables for an MCP server. ```json "env": { "BRAVE_API_KEY": "your-key", "DEBUG": "true" } ``` -------------------------------- ### Run Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md Python code to execute the asynchronous function `load_fetch_tools`. ```python # Run asyncio.run(load_fetch_tools()) ``` -------------------------------- ### Clipboard Not Working Error and Fix Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md Troubleshooting and fixing clipboard issues on different operating systems by installing necessary tools. ```bash # Error: Error accessing clipboard # Linux: Install xclip sudo apt install xclip # macOS: Install pngpaste for images brew install pngpaste # Windows: Ensure PowerShell available powershell.exe -Command "Get-Clipboard" # Retry llm cb "Analyze this" ``` -------------------------------- ### Get memories Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md Python code to retrieve conversation memories from the storage system. It initializes an `SqliteStore` and then uses `get_memories` to fetch them. ```python import asyncio from pathlib import Path from mcp_client_cli.storage import ConversationManager, SqliteStore from mcp_client_cli.memory import get_memories async def check_memories(): db_path = Path.home() / ".llm" / "conversations.db" # Get memories store = SqliteStore(db_path) memories = await get_memories(store) ``` -------------------------------- ### Get clipboard content Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/input.md Example of how to use the `get_clipboard_content` function to retrieve text or image data from the clipboard and handle potential errors. ```python from mcp_client_cli.input import get_clipboard_content # Get text from clipboard result = get_clipboard_content() if result: content, mime_type = result if mime_type is None: print(f"Text: {content}") else: print(f"Image ({mime_type}): {len(content)} bytes") # Use in CLI try: content, mime_type = get_clipboard_content() if mime_type: # It's an image image_base64 = base64.b64encode(content).decode('utf-8') # Send to LLM with image else: # It's text # Process as text except Exception as e: print(f"Clipboard error: {e}") ``` -------------------------------- ### Get enabled servers Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md Python code iterating through the enabled servers defined in the configuration and printing their names, commands, and enabled status. ```python # Get enabled servers for name, server_config in config.get_enabled_servers().items(): print(f"Server: {name}") print(f" Command: {server_config.command}") print(f" Enabled: {server_config.enabled}") ``` -------------------------------- ### Text-only output with final message only Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md This command demonstrates how to get text-only output from the LLM, suppressing intermediate steps and redirecting the final result to a file. ```bash llm --text-only --no-intermediates "question" >> results.txt ``` -------------------------------- ### Input Modes Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/README.md Examples of different input modes for the CLI. ```bash # Standard input llm < file.txt # Read from file cat image.jpg | llm "describe" # Pipe image echo "text" | llm "process" # Pipe text # Clipboard llm cb # From clipboard llm cb "describe" # Clipboard with prompt # Templates llm p yt url=https://... # YouTube template ``` -------------------------------- ### OutputHandler confirm_tool_call() Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/output.md Illustrates the process of confirming tool calls with user interaction. ```python config = app_config.__dict__ # Convert dataclass to dict output = OutputHandler() output.start() async for chunk in agent.astream(...): output.update(chunk) if not output.confirm_tool_call(config, chunk): break # User denied tool execution output.finish() ``` -------------------------------- ### parse_query Examples Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/cli.md Examples illustrating how the parse_query function interprets different command-line inputs to determine the user's message and conversation continuation status. ```bash $ llm "What is Python?" # Returns: (HumanMessage("What is Python?"), False) $ llm c "Tell me more" # Returns: (HumanMessage("Tell me more"), True) $ cat code.py | llm "Explain this code" # Returns: (HuvenMessage([{"type": "text", "text": "Explain..."}]), False) ``` -------------------------------- ### Tool Call Display Format Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/output.md Example of how tool calls are displayed in the console. ```text ### Tool Calls: tool_name (call_id) Args: param1: value1 param2: value2 ``` -------------------------------- ### Usage of SQLITE_DB Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/constants.md Example showing how to initialize ConversationManager with the SQLITE_DB path. ```python from mcp_client_cli.const import SQLITE_DB from mcp_client_cli.storage import ConversationManager manager = ConversationManager(SQLITE_DB) ``` -------------------------------- ### Important: cleanup Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md A reminder to close the toolkit after use to release resources. ```python # Important: cleanup await toolkit.close() ``` -------------------------------- ### Concurrent Task Execution with AnyIO Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/architecture.md Demonstrates using AnyIO task groups for concurrent initialization of MCP servers. ```python async with anyio.create_task_group() as tg: for server_config in server_configs: tg.start_soon(initialize_server, server_config) ``` -------------------------------- ### Formatting memories for agent context Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/memory.md Example of how memories are formatted before being passed to the agent as context. ```python formatted_memories = "\n".join(f"- {memory}" for memory in memories) # Passed to agent as context ``` -------------------------------- ### Quick Conversion Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md Quickly converting clipboard content, e.g., JSON to Python. ```bash # Copy JSON to clipboard # Then convert to Python llm cb "Convert this JSON to Python dictionary" # Process without explicit question (uses default) llm cb ``` -------------------------------- ### Configuration Loading Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/README.md Demonstrates how to load the application configuration. ```python from mcp_client_cli.config import AppConfig config = AppConfig.load() # Searches: ./mcp-server-config.json, ~/.llm/config.json ``` -------------------------------- ### Install via pip Source: https://github.com/adhikasp/mcp-client-cli/blob/master/README.md Installs the mcp-client-cli package using pip. ```bash pip install mcp-client-cli ``` -------------------------------- ### RecursionError Recovery Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/errors.md Example of how to increase remaining_steps in AgentState to mitigate RecursionError. ```python # In agent initialization input_messages = AgentState( messages=[query], remaining_steps=10 # Increase from default 5 ) ``` -------------------------------- ### Usage of CACHE_DIR Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/constants.md Example demonstrating how to construct a cache file path using CACHE_DIR. ```python from mcp_client_cli.const import CACHE_DIR # Cache location cache_file = CACHE_DIR / "fetch-uvx-mcp-server-fetch.json" ``` -------------------------------- ### MCP Server Enabled Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/configuration.md Example JSON snippet to disable an MCP server. ```json "enabled": false ``` -------------------------------- ### Async Entry Point and Main Function Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/architecture.md Example of the application's asynchronous entry point and main execution function. ```python # Entry point def main() -> None: asyncio.run(run()) # Execute async function # Main async function async def run() -> None: config = AppConfig.load() # Sync config loading await handle_conversation(...) # Async handler ``` -------------------------------- ### OutputHandler Constructor Examples Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/output.md Demonstrates different ways to instantiate the OutputHandler class based on desired output behavior. ```python from mcp_client_cli.output import OutputHandler # Standard markdown-formatted output with all messages output = OutputHandler() # Raw text output output = OutputHandler(text_only=True) # Only final message, useful for scripts output = OutputHandler(text_only=True, only_last_message=True) ``` -------------------------------- ### Cache File Structure Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/storage.md Example JSON structure of a cached tools file. ```json { "cached_at": "2024-01-01T12:00:00", "tools": [ { "name": "fetch", "description": "Fetch web content", "inputSchema": { ... } } ] } ``` -------------------------------- ### save_memory example usage Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/memory.md Example of how to use the save_memory tool within an agent execution context. ```python # Used within agent execution context # The agent calls this tool automatically result = await save_memory( ["The user prefers concise responses", "User timezone is UTC"], config=config, store=store ) # Returns: "Saved memories: ['The user...', 'User timezone...']" ``` -------------------------------- ### Custom Output Handler Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/architecture.md Shows how to create a custom output handler to format agent output as JSON. ```python class JSONOutputHandler: def update(self, chunk): # Output as JSON instead of markdown pass output = JSONOutputHandler() output.start() ``` -------------------------------- ### Override model in config Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md Example of overriding the default LLM model to 'gpt-3.5-turbo' for a specific query. ```bash # Override model in config llm --model gpt-3.5-turbo "Quick question" ``` -------------------------------- ### setup_argument_parser() function signature Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/cli.md Sets up and returns the argument parser for the CLI. ```python def setup_argument_parser() -> argparse.Namespace ``` -------------------------------- ### Create config in project directory Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md Shows how to create a project-specific LLM configuration file (`config.json`) within a project's directory (`project/.llm/`). This configuration includes settings for the system prompt, LLM provider and model, and MCP server definitions. ```bash # Create config in project directory mkdir -p project/.llm cat > project/.llm/config.json << 'EOF' { "systemPrompt": "You are a Python expert helping with this project.", "llm": { "provider": "openai", "model": "gpt-4" }, "mcpServers": { "fetch": { "command": "uvx", "args": ["mcp-server-fetch"] } } } EOF ``` -------------------------------- ### Tool Confirmation Workflow Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md Illustrates the workflow for confirming tool calls before execution, allowing users to review details. ```bash # First: see what tools will be used llm "Execute this command for me" # Shows: "Confirm tool call? [y/n]" # Review tool call details, then approve ``` -------------------------------- ### Create server config Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md Python code to create an `McpServerConfig` object for the 'fetch' server, specifying its parameters including the command and arguments. ```python from mcp import StdioServerParameters from mcp_client_cli.tool import convert_mcp_to_langchain_tools, McpServerConfig # Create server config server_config = McpServerConfig( server_name="fetch", server_param=StdioServerParameters( command="uvx", args=["mcp-server-fetch"], env={} ) ) ``` -------------------------------- ### Agent saving memories example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/memory.md An example illustrating how an agent might decide to save memories during execution. ```python # Within agent execution, the LLM can decide to save memories # Example: # Agent: "I'll remember that you prefer JSON output." # [Tool Call: save_memory(["User prefers JSON output"])] ``` -------------------------------- ### get_memories example usage Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/memory.md Example of how to use the get_memories function to retrieve all memories or memories matching a query. ```python from mcp_client_cli.memory import get_memories store = SqliteStore(db_path, index=index_config) # Get all memories all_memories = await get_memories(store) # Get memories matching query relevant = await get_memories(store, query="timezone preferences") ``` -------------------------------- ### create_langchain_tool Function Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/tool.md Example of creating a LangChain tool from an MCP tool schema. ```python from mcp_client_cli.tool import create_langchain_tool # After getting tool_schema from MCP server langchain_tool = create_langchain_tool(tool_schema, session, toolkit) ``` -------------------------------- ### _arun Method Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/tool.md Example of how to invoke the _arun method asynchronously to execute a tool. ```python # Tool is typically invoked through LangChain framework result = await tool._arun(url="https://example.com") # result is JSON string ``` -------------------------------- ### McpToolkit.get_tools Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/tool.md Example usage of the get_tools method for McpToolkit to list available tools. ```python await toolkit.initialize() tools = toolkit.get_tools() for tool in tools: print(f"Tool: {tool.name}") print(f"Description: {tool.description}") ``` -------------------------------- ### Storage Initialization Flow Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/architecture.md Diagram illustrating the process of initializing the storage database, including table creation and persistence. ```text First run or new database ↓ ConversationManager.get_last_id() ↓ Check: database file exists? ↓ If no: _init_db() creates schema ↓ Create tables: ├─ last_conversation ├─ items └─ vectors (if index configured) ↓ Insert/query as needed ↓ Persist across sessions ``` -------------------------------- ### MCP Server Exclude Tools Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/configuration.md Example JSON snippet to exclude specific tools from an MCP server. ```json "exclude_tools": ["delete_file", "format_drive"] ``` -------------------------------- ### Initialize toolkit Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md Python code to initialize a toolkit from an `McpServerConfig` object, which will be used to convert MCP server definitions into Langchain tools. ```python # Initialize toolkit toolkit = await convert_mcp_to_langchain_tools(server_config) ``` -------------------------------- ### ConversationManager get_last_id() Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/storage.md Example of using get_last_id() to retrieve or create a thread ID for continuing a conversation. ```python manager = ConversationManager(db_path) # Get or create thread ID for continuing conversation thread_id = await manager.get_last_id() ``` -------------------------------- ### Load configuration Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/usage-patterns.md Python code snippet demonstrating how to load the application configuration using the `AppConfig.load()` method. ```python from mcp_client_cli.config import AppConfig # Load configuration config = AppConfig.load() ``` -------------------------------- ### convert_mcp_to_langchain_tools Function Example Source: https://github.com/adhikasp/mcp-client-cli/blob/master/_autodocs/api-reference/tool.md Example of converting MCP tools to LangChain tools and creating a toolkit. ```python from mcp_client_cli.tool import convert_mcp_to_langchain_tools server_config = McpServerConfig( server_name="fetch", server_param=server_param ) toolkit = await convert_mcp_to_langchain_tools(server_config) tools = toolkit.get_tools() # Later cleanup await toolkit.close() ```