### Project Setup for Windows Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Creates a new project directory, initializes an npm project, installs necessary dependencies, and sets up source files for Windows environments. ```powershell # Create a new directory for our project md weather cd weather # Initialize a new npm project npm init -y # Install dependencies npm install @modelcontextprotocol/sdk zod npm install -D @types/node typescript # Create our files md src new-item src\index.ts ``` -------------------------------- ### Project Setup for MacOS/Linux Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Creates a new project directory, initializes an npm project, installs necessary dependencies, and sets up source files for MacOS and Linux environments. ```bash # Create a new directory for our project mkdir weather cd weather # Initialize a new npm project npm init -y # Install dependencies npm install @modelcontextprotocol/sdk zod npm install -D @types/node typescript # Create our files mkdir src touch src/index.ts ``` -------------------------------- ### Node.js Project Setup (Windows) Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Commands to set up a new Node.js project for MCP client development on Windows. Includes creating directories, initializing npm, and installing dependencies. ```powershell # Create project directory md mcp-client-typescript cd mcp-client-typescript # Initialize npm project npm init -y # Install dependencies npm install @anthropic-ai/sdk @modelcontextprotocol/sdk dotenv # Install dev dependencies npm install -D @types/node typescript # Create source file new-item index.ts ``` -------------------------------- ### Node.js Project Setup (MacOS/Linux) Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Commands to set up a new Node.js project for MCP client development on MacOS or Linux. Includes creating directories, initializing npm, and installing dependencies. ```bash # Create project directory mkdir mcp-client-typescript cd mcp-client-typescript # Initialize npm project npm init -y # Install dependencies npm install @anthropic-ai/sdk @modelcontextprotocol/sdk dotenv # Install dev dependencies npm install -D @types/node typescript # Create source file touch index.ts ``` -------------------------------- ### Install Dependencies and Build Project Source: https://github.com/claude-did-this/mcpcontrol/blob/main/CONTRIBUTING.md Install project dependencies and build the project using npm scripts. ```bash # Install dependencies npm install # Build the project npm run build ``` -------------------------------- ### Install Python Source: https://github.com/claude-did-this/mcpcontrol/blob/main/README.md Installs Python 3.12 using winget. This is a prerequisite for node-gyp. ```powershell # Install Python (required for node-gyp) winget install Python.Python.3.12 ``` -------------------------------- ### Install Node.js Source: https://github.com/claude-did-this/mcpcontrol/blob/main/README.md Installs the latest LTS version of Node.js using winget. ```powershell # Install latest LTS version winget install OpenJS.NodeJS ``` -------------------------------- ### Clone Example Repository Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Clones the spring-ai-examples repository and navigates into the brave-chatbot directory. ```bash git clone https://github.com/spring-projects/spring-ai-examples.git cd model-context-protocol/brave-chatbot ``` -------------------------------- ### Install uv package manager Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Installs the uv package manager. This is a prerequisite for setting up the Python environment. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` ```powershell powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" ``` -------------------------------- ### Install MCPControl Package Source: https://github.com/claude-did-this/mcpcontrol/blob/main/README.md Installs the MCPControl package globally using npm. ```bash npm install -g mcp-control ``` -------------------------------- ### Initialize and set up Python MCP project Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Creates a new project directory, sets up a virtual environment, installs MCP and httpx dependencies, and creates the main server file. ```bash # Create a new directory for our project uv init weather cd weather # Create virtual environment and activate it uv venv source .venv/bin/activate # Install dependencies uv add "mcp[cli]" httpx # Create our server file touch weather.py ``` ```powershell # Create a new directory for our project uv init weather cd weather # Create virtual environment and activate it uv venv .venv\Scripts\activate # Install dependencies uv add mcp[cli] httpx # Create our server file new-item weather.py ``` -------------------------------- ### MCP Server Setup with Stdio Transport (Python) Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Instantiate an MCP server and run it using the stdio transport. This asynchronous setup handles communication over standard input and output streams. ```python app = Server("example-server") async with stdio_server() as streams: await app.run( streams[0], streams[1], app.create_initialization_options() ) ``` -------------------------------- ### Example Implementation with Language and Code Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt This snippet shows a Python implementation for generating a prompt that explains a given code snippet in a specified language. It's used within a tabbed interface for displaying code examples. ```python from typing import List def generate_explanation_prompt(language: str, code: str) -> str: """Generates a prompt to explain code in a specific language.""" return f"Explain how this {language} code works:\n\n{code}" ``` -------------------------------- ### Import Packages and Setup MCP Server Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Initializes the MCP server instance with basic configuration and imports necessary SDK components and utility libraries. ```typescript import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { z } from "zod"; const NWS_API_BASE = "https://api.weather.gov"; const USER_AGENT = "weather-app/1.0"; // Create server instance const server = new McpServer({ name: "weather", version: "1.0.0", }); ``` -------------------------------- ### TypeScript MCP Server Prompt Implementation Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Implement prompt listing and retrieval handlers for an MCP server using TypeScript. This example defines two prompts: 'git-commit' and 'explain-code', and sets up request handlers for listing all prompts and getting specific prompt details. ```typescript import { Server } from "@modelcontextprotocol/sdk/server"; import { ListPromptsRequestSchema, GetPromptRequestSchema } from "@modelcontextprotocol/sdk/types"; const PROMPTS = { "git-commit": { name: "git-commit", description: "Generate a Git commit message", arguments: [ { name: "changes", description: "Git diff or description of changes", required: true } ] }, "explain-code": { name: "explain-code", description: "Explain how code works", arguments: [ { name: "code", description: "Code to explain", required: true }, { name: "language", description: "Programming language", required: false } ] } }; const server = new Server({ name: "example-prompts-server", version: "1.0.0" }, { capabilities: { prompts: {} } }); // List available prompts server.setRequestHandler(ListPromptsRequestSchema, async () => { return { prompts: Object.values(PROMPTS) }; }); // Get specific prompt server.setRequestHandler(GetPromptRequestSchema, async (request) => { const prompt = PROMPTS[request.params.name]; if (!prompt) { throw new Error(`Prompt not found: ${request.params.name}`); } if (request.params.name === "git-commit") { return { messages: [ { role: "user", content: { type: "text", text: `Generate a concise but descriptive commit message for these changes:\n\n${request.params.arguments?.changes}` } } ] }; } if (request.params.name === "explain-code") { const language = request.params.arguments?.language || "Unknown"; return { messages: [ { role: "user", content: { type: "text", text: `Explain how this ${language} code works:\n\n${request.params.arguments?.code}` } } ] }; } throw new Error("Prompt implementation not found"); }); ``` -------------------------------- ### Run Git MCP Server with uvx Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Install and run the Git MCP server using `uvx`. This is the recommended method for Python-based servers. ```bash uvx mcp-server-git ``` -------------------------------- ### Initialize MCP Client Environment Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Sets up a new Python project using uv, creates a virtual environment, and installs necessary packages like mcp, anthropic, and python-dotenv. ```bash uv init mcp-client cd mcp-client uv venv # On Windows: .venv\Scripts\activate # On Unix or MacOS: source .venv/bin/activate uv add mcp anthropic python-dotenv rm hello.py touch client.py ``` -------------------------------- ### Main Entry Point for Client Execution Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Sets up and runs the main client application. It handles command-line arguments for the server script, initializes the client, connects to the server, and starts the chat loop, ensuring cleanup. ```python async def main(): if len(sys.argv) < 2: print("Usage: python client.py ") sys.exit(1) client = MCPClient() try: await client.connect_to_server(sys.argv[1]) await client.chat_loop() finally: await client.cleanup() if __name__ == "__main__": import sys import asyncio asyncio.run(main()) ``` -------------------------------- ### Install and Run Git MCP Server with pip Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Install the Git MCP server using `pip` and then run it using `python -m`. This is an alternative method for Python-based servers. ```bash pip install mcp-server-git python -m mcp_server_git ``` -------------------------------- ### Install Build Tools Source: https://github.com/claude-did-this/mcpcontrol/blob/main/README.md Installs Visual Studio 2022 Build Tools with the VC++ workload. Run this command as an administrator. ```powershell # Run as Administrator - may take a few minutes to complete winget install Microsoft.VisualStudio.2022.BuildTools --override "--wait --passive --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended" ``` -------------------------------- ### Verify Node.js Installation Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Command to check the installed version of Node.js. Requires Node.js and npm to be installed. ```bash node --version ``` -------------------------------- ### Check Node.js Version Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Verify that Node.js version 16 or higher is installed, which is required for this tutorial. ```bash npm --version ``` -------------------------------- ### Example MCP Server Description Prompt Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Provides an example prompt to describe the desired MCP server functionality to Claude, including database connections, resource exposure, tool provision, and prompt integration. ```plaintext Build an MCP server that: - Connects to my company's PostgreSQL database - Exposes table schemas as resources - Provides tools for running read-only SQL queries - Includes prompts for common data analysis tasks ``` -------------------------------- ### Run Memory MCP Server Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Use the `npx` command to run the memory-based MCP server directly. This is a quick way to start using MCP servers without local installation. ```bash npx -y @modelcontextprotocol/server-memory ``` -------------------------------- ### Node.js EventSource Client Setup Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/sse-transport.md Instructions for setting up an EventSource client in Node.js (CommonJS) using the 'eventsource' package, as Node.js does not have a native EventSource implementation. ```bash npm i eventsource # vendored in repo for offline use ``` ```javascript const EventSource = require('eventsource'); const es = new EventSource('http://localhost:3232/mcp/sse?auth=' + token); ``` -------------------------------- ### Install and Run MCP Inspector Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Run the MCP Inspector directly using npx without global installation. Replace `` with the desired Inspector command. ```bash npx @modelcontextprotocol/inspector ``` -------------------------------- ### Basic MCP Server Implementation in TypeScript Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt A fundamental example demonstrating how to set up an MCP server in TypeScript, define capabilities, and handle resource listing requests. Requires the @modelcontextprotocol/sdk. ```typescript import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; const server = new Server({ name: "example-server", version: "1.0.0" }, { capabilities: { resources: {} } }); // Handle requests server.setRequestHandler(ListResourcesRequestSchema, async () => { return { resources: [ { uri: "example://resource", name: "Example Resource" } ] }; }); // Connect transport const transport = new StdioServerTransport(); await server.connect(transport); ``` -------------------------------- ### Configure MCP Servers in JSON Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Add MCP servers to your configuration file. This example shows how to configure memory, filesystem, and GitHub servers, including environment variables for authentication. ```json { "mcpServers": { "memory": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-memory"] }, "filesystem": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/files"] }, "github": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"], "env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "" } } } } ``` -------------------------------- ### Install npx Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Installs the npx package globally, which is required for running Node.js packages from the command line. ```bash npm install -g npx ``` -------------------------------- ### Example of Correct Server Path Usage Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Illustrates correct ways to specify server paths, including relative, absolute, and Windows-specific formats. Use forward slashes or escaped backslashes for Windows paths. ```bash # Relative path node build/index.js ./server/build/index.js # Absolute path node build/index.js /Users/username/projects/mcp-server/build/index.js # Windows path (either format works) node build/index.js C:/projects/mcp-server/build/index.js node build/index.js C:\\projects\\mcp-server\\build\\index.js ``` -------------------------------- ### MCP Roots Configuration Example Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt This JSON configuration demonstrates how a typical MCP client might expose roots for local repositories and API endpoints. ```json { "roots": [ { "uri": "file:///home/user/projects/frontend", "name": "Frontend Repository" }, { "uri": "https://api.example.com/v1", "name": "API Endpoint" } ] } ``` -------------------------------- ### Initialize FastMCP server instance Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Initializes the FastMCP server instance with a given name. This is the starting point for building an MCP server. ```python from typing import Any import httpx from mcp.server.fastmcp import FastMCP # Initialize FastMCP server mcp = FastMCP("weather") # Constants NWS_API_BASE = "https://api.weather.gov" USER_AGENT = "weather-app/1.0" ``` -------------------------------- ### Install NPM Globally Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Command to install NPM globally, which may be required for `npx` commands to function correctly. This ensures that package executables are available system-wide. ```bash npm install -g npm ``` -------------------------------- ### Example Resource URIs Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Illustrates different types of resource URIs, including file, database, and screen-based protocols. ```plaintext [protocol]://[host]/[path] ``` ```plaintext file:///home/user/documents/report.pdf ``` ```plaintext postgres://database/customers/schema ``` ```plaintext screen://localhost/display1 ``` -------------------------------- ### Basic MCP Server Implementation in Python Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt A basic example of an MCP server in Python, showcasing how to define a server instance and a resource listing handler using decorators. Requires the mcp library. ```python import asyncio import mcp.types as types from mcp.server import Server from mcp.server.stdio import stdio_server app = Server("example-server") @app.list_resources() async def list_resources() -> list[types.Resource]: return [ types.Resource( uri="example://resource", name="Example Resource" ) ] async def main(): async with stdio_server() as streams: await app.run( streams[0], streams[1], app.create_initialization_options() ) if __name__ == "__main__": asyncio.run(main) ``` -------------------------------- ### Browser EventSource Client Example Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/sse-transport.md Example of how to connect to the SSE endpoint from a web browser using the native EventSource API. Handles connection opening, general messages, and specific 'mcp.response' events. ```javascript const es = new EventSource('/mcp/sse?auth=' + jwt); es.onopen = () => console.log('open'); es.onmessage = (e) => console.log(JSON.parse(e.data)); es.addEventListener('mcp.response', ({ data }) => { const { requestId, data: body } = JSON.parse(data); }); ``` -------------------------------- ### Example Sampling Request Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Demonstrates a JSON structure for requesting sampling from a client, including messages, system prompt, context inclusion, and token limits. ```json { "method": "sampling/createMessage", "params": { "messages": [ { "role": "user", "content": { "type": "text", "text": "What files are in the current directory?" } } ], "systemPrompt": "You are a helpful file system assistant.", "includeContext": "thisServer", "maxTokens": 100 } } ``` -------------------------------- ### Production deployment with HTTPS and SSE Source: https://github.com/claude-did-this/mcpcontrol/blob/main/RELEASE_NOTES_v0.2.0.md Example command for running mcp-control in a production environment, utilizing both SSE transport and HTTPS/TLS with specified certificate and key files. ```bash mcp-control --sse --https --cert cert.pem --key key.pem ``` -------------------------------- ### Inspect PyPi Server Package Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Inspect an MCP server package published on PyPi. This example uses npx to run the Inspector and then uvx to execute a Python package. ```bash npx @modelcontextprotocol/inspector uvx # For example npx @modelcontextprotocol/inspector uvx mcp-server-git --repository ~/code/mcp/servers.git ``` -------------------------------- ### Run Application with Maven Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Runs the Spring Boot application using the Maven wrapper. This is a convenient way to start the application during development. ```bash ./mvnw spring-boot:run ``` -------------------------------- ### Modular Configuration with AutoHotkey Providers Source: https://github.com/claude-did-this/mcpcontrol/blob/main/src/providers/autohotkey/README.md Configure specific automation modules (keyboard, mouse, screen, clipboard) to use AutoHotkey in a modular setup. ```javascript const provider = createAutomationProvider({ providers: { keyboard: 'autohotkey', mouse: 'autohotkey', screen: 'autohotkey', clipboard: 'autohotkey', }, }); ``` -------------------------------- ### MCP Server Setup with Stdio Transport (TypeScript) Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Initialize an MCP server and connect it to a stdio transport for communication via standard input/output streams. This is suitable for local integrations and command-line tools. ```typescript const server = new Server({ name: "example-server", version: "1.0.0" }, { capabilities: {} }); const transport = new StdioServerTransport(); await server.connect(transport); ``` -------------------------------- ### Run MCPControl with HTTPS on Custom Port Source: https://github.com/claude-did-this/mcpcontrol/blob/main/README.md Starts the MCPControl server with SSE transport and HTTPS/TLS enabled on a custom port. Certificate and key paths are required. ```bash mcp-control --sse --https --port 8443 --cert /path/to/cert.pem --key /path/to/key.pem ``` -------------------------------- ### MCP Client Setup with Stdio Transport (Python) Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Establish an MCP client connection using the stdio transport. This involves defining server parameters and managing the client session asynchronously. ```python params = StdioServerParameters( command="./server", args=["--option", "value"] ) async with stdio_client(params) as streams: async with ClientSession(streams[0], streams[1]) as session: await session.initialize() ``` -------------------------------- ### Inspect NPM Server Package Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Inspect an MCP server package published on NPM. This example uses npx to run the Inspector and then execute an NPM package. ```bash npx -y @modelcontextprotocol/inspector npx # For example npx -y @modelcontextprotocol/inspector npx server-postgres postgres://127.0.0.1/testdb ``` -------------------------------- ### List and Execute Prompts (Sync) Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Interact with the prompt system using the synchronous API to discover prompt templates and execute them with custom parameters. The 'echo' prompt is used here as an example. ```java var prompts = client.listPrompts(); prompts.forEach(prompt -> System.out.println(prompt.getName())); var response = client.executePrompt("echo", Map.of( "text", "Hello, World!" )); ``` -------------------------------- ### MCP Client Setup with Stdio Transport (TypeScript) Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Configure an MCP client to connect to a server using the stdio transport. Specify the command to execute for the server and any necessary arguments. ```typescript const client = new Client({ name: "example-client", version: "1.0.0" }, { capabilities: {} }); const transport = new StdioClientTransport({ command: "./server", args: ["--option", "value"] }); await client.connect(transport); ``` -------------------------------- ### Python MCP Server Prompt Implementation Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Implement prompt listing and retrieval handlers for an MCP server using Python. This example defines two prompts, 'git-commit' and 'explain-code', and sets up asynchronous request handlers for listing prompts and retrieving prompt details. ```python from mcp.server import Server import mcp.types as types # Define available prompts PROMPTS = { "git-commit": types.Prompt( name="git-commit", description="Generate a Git commit message", arguments=[ types.PromptArgument( name="changes", description="Git diff or description of changes", required=True ) ], ), "explain-code": types.Prompt( name="explain-code", description="Explain how code works", arguments=[ types.PromptArgument( name="code", description="Code to explain", required=True ), types.PromptArgument( name="language", description="Programming language", required=False ) ], ) } # Initialize server app = Server("example-prompts-server") @app.list_prompts() async def list_prompts() -> list[types.Prompt]: return list(PROMPTS.values()) @app.get_prompt() async def get_prompt( name: str, arguments: dict[str, str] | None = None ) -> types.GetPromptResult: if name not in PROMPTS: raise ValueError(f"Prompt not found: {name}") if name == "git-commit": changes = arguments.get("changes") if arguments else "" return types.GetPromptResult( messages=[ types.PromptMessage( role="user", content=types.TextContent( type="text", text=f"Generate a concise but descriptive commit message " f"for these changes:\n\n{changes}" ) ) ] ) if name == "explain-code": code = arguments.get("code") if arguments else "" language = arguments.get("language", "Unknown") if arguments else "Unknown" return types.GetPromptResult( messages=[ types.PromptMessage( role="user", content=types.TextContent( type="text", ``` -------------------------------- ### Configure Environment Variables for MCP Server Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Example JSON configuration for an MCP server, including environment variables like APPDATA and API keys. This is useful when paths are not resolving correctly on Windows. ```json { "brave-search": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-brave-search"], "env": { "APPDATA": "C:\\Users\\user\\AppData\\Roaming\\", "BRAVE_API_KEY": "..." } } } ``` -------------------------------- ### MCP Prompt Discovery Response Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Example response from an MCP server listing available prompts, including their names, descriptions, and required arguments. Demonstrates the structure for a 'analyze-code' prompt. ```json { "prompts": [ { "name": "analyze-code", "description": "Analyze code for potential improvements", "arguments": [ { "name": "language", "description": "Programming language", "required": true } ] } ] } ``` -------------------------------- ### Configure MCP Servers in Claude for Desktop (JSON) Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Add your MCP servers to the `mcpServers` key in the Claude configuration file. This example shows how to configure a 'weather' server using Node.js. ```json { "mcpServers": { "weather": { "command": "node", "args": [ "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/index.js" ] } } } ``` ```json { "mcpServers": { "weather": { "command": "node", "args": [ "C:\\PATH\\TO\\PARENT\\FOLDER\\weather\\build\\index.js" ] } } } ``` -------------------------------- ### Configure MCP Client Boot Starter Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Illustrates how to configure the MCP client boot starter by setting the server configuration property to point to the client's configuration file. ```properties spring.ai.mcp.client.stdio.servers-configuration=file:PATH/TO/claude_desktop_config.json ``` -------------------------------- ### Run mcp-control with HTTPS/TLS Source: https://github.com/claude-did-this/mcpcontrol/blob/main/RELEASE_NOTES_v0.2.0.md Start the mcp-control service with SSE transport, enabling HTTPS/TLS for secure connections. You must provide paths to your certificate and key files. HTTPS is required for production deployments. ```bash mcp-control --sse --https --cert /path/to/cert.pem --key /path/to/key.pem ``` -------------------------------- ### Running Client with Server Script (Bash) Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Demonstrates how to run the client script, specifying the server script path. Supports both relative and absolute paths, including Windows-style paths. ```bash # Relative path uv run client.py ./server/weather.py ``` ```bash # Absolute path uv run client.py /Users/username/projects/mcp-server/weather.py ``` ```bash # Windows path (either format works) uv run client.py C:/projects/mcp-server/weather.py ``` ```bash uv run client.py C:\\projects\\mcp-server\\weather.py ``` -------------------------------- ### Implement Basic Tool Server (Python) Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Set up an MCP server using Python decorators to manage tool definitions and execution. This approach simplifies tool registration and handling. ```python app = Server("example-server") @app.list_tools() async def list_tools() -> list[types.Tool]: return [ types.Tool( name="calculate_sum", description="Add two numbers together", inputSchema={ "type": "object", "properties": { "a": {"type": "number"}, "b": {"type": "number"} }, "required": ["a", "b"] } ) ] @app.call_tool() async def call_tool( name: str, arguments: dict ) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]: if name == "calculate_sum": a = arguments["a"] b = arguments["b"] result = a + b return [types.TextContent(type="text", text=str(result))] raise ValueError(f"Tool not found: {name}") ``` -------------------------------- ### Get Prompt Request and Response Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Demonstrates a typical request to get a prompt and the expected response structure, including user messages with embedded code for analysis. ```typescript // Request { method: "prompts/get", params: { name: "analyze-code", arguments: { language: "python" } } } // Response { description: "Analyze Python code for potential improvements", messages: [ { role: "user", content: { type: "text", text: "Please analyze the following Python code for potential improvements:\n\n```python\ndef calculate_sum(numbers):\n total = 0\n for num in numbers:\n total = total + num\n return total\n\nresult = calculate_sum([1, 2, 3, 4, 5])\nprint(result)"" } } ] } ``` -------------------------------- ### Install Latest Stable Release Source: https://github.com/claude-did-this/mcpcontrol/blob/main/README.md Install the most recent stable version of MCPControl from the release branch using npm. This command fetches the version tagged for stable releases. ```bash npm install mcp-control ``` -------------------------------- ### Install Specific Version Source: https://github.com/claude-did-this/mcpcontrol/blob/main/README.md Install a particular version of MCPControl using npm by specifying the version number after the package name. This is useful for maintaining compatibility with specific project requirements. ```bash npm install mcp-control@0.1.22 ``` -------------------------------- ### Create and Configure Async MCP Server Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Instantiate an asynchronous MCP server with custom configurations. This includes setting server information, defining capabilities, and building the server instance. ```java McpAsyncServer asyncServer = McpServer.async(transport) .serverInfo("my-server", "1.0.0") .capabilities(ServerCapabilities.builder() .resources(true) // Enable resource support .tools(true) // Enable tool support .prompts(true) // Enable prompt support .logging() // Enable logging support .build()) .build(); ``` -------------------------------- ### Call MCP Client Tools Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Demonstrates how to use the MCP client to call tools with specific parameters and close the client gracefully. ```java CallToolResult alert = mcpClient.callTool( new CallToolRequest("getAlerts", Map.of("state", "NY"))); mcpClient.closeGracefully(); ``` -------------------------------- ### Create and Configure Sync MCP Server Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Use this snippet to create a synchronous MCP server instance. Configure server information, capabilities like resources, tools, and prompts, and then build the server. ```java McpSyncServer syncServer = McpServer.sync(transport) .serverInfo("my-server", "1.0.0") .capabilities(ServerCapabilities.builder() .resources(true) // Enable resource support .tools(true) // Enable tool support .prompts(true) // Enable prompt support .logging() // Enable logging support .build()) .build(); ``` -------------------------------- ### Run mcp-control with a custom port Source: https://github.com/claude-did-this/mcpcontrol/blob/main/RELEASE_NOTES_v0.2.0.md Start the mcp-control service with SSE transport on a custom port. The default port is 3232. ```bash mcp-control --sse --port 3000 ``` -------------------------------- ### MCP Prompt Discovery Request Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Example of a client request to discover available prompts on an MCP server. This is a standard JSON-RPC request. ```json { "method": "prompts/list" } ``` -------------------------------- ### Register Tools, Resources, and Prompts (Async) Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Register asynchronous tools, resources, and prompts with the MCP server. Subscribe to the returned Mono to observe registration success or handle errors. ```java asyncServer.addTool(asyncToolRegistration) .doOnSuccess(v -> logger.info("Tool registered")) .subscribe(); asyncServer.addResource(asyncResourceRegistration) .doOnSuccess(v -> logger.info("Resource registered")) .subscribe(); asyncServer.addPrompt(asyncPromptRegistration) .doOnSuccess(v -> logger.info("Prompt registered")) .subscribe(); ``` -------------------------------- ### Get Active Alerts Tool Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Defines a tool to retrieve and format active alerts for a given state code. It handles cases with no active alerts. ```typescript server.tool( "get-alerts", "Get active alerts for a state", { stateCode: z.string().describe("The state code (e.g., CA, TX)") }, async ({ stateCode }) => { const alertsUrl = `${NWS_API_BASE}/alerts/active/states/${stateCode}`; const alertsData = await makeNWSRequest(alertsUrl); if (!alertsData) { return { content: [ { type: "text", text: `Failed to retrieve alerts for state code: ${stateCode}. This state may not be supported by the NWS API (only US states are supported).`, }, ], }; } const features = alertsData.features || []; if (features.length === 0) { return { content: [ { type: "text", text: `No active alerts for ${stateCode}`, }, ], }; } const formattedAlerts = features.map(formatAlert); const alertsText = `Active alerts for ${stateCode}:\n\n${formattedAlerts.join("\n")}`; return { content: [ { type: "text", text: alertsText, }, ], }; }, ); ``` -------------------------------- ### Configure Client Capabilities Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Builds client capabilities, enabling features like filesystem roots support and LLM sampling. ```java var capabilities = ClientCapabilities.builder() .roots(true) // Enable filesystem roots support with list changes notifications .sampling() // Enable LLM sampling support .build(); ``` -------------------------------- ### Register Tools, Resources, and Prompts (Sync) Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt After creating a sync MCP server, register your custom tools, resources, and prompts using the respective add methods. ```java syncServer.addTool(syncToolRegistration); syncServer.addResource(syncResourceRegistration); syncServer.addPrompt(syncPromptRegistration); ``` -------------------------------- ### Build Application with Maven Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Builds the application using the Maven wrapper script. This command compiles the code and packages it. ```bash ./mvnw clean install ``` -------------------------------- ### Select Keysender Provider Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/providers.md Set the AUTOMATION_PROVIDER environment variable to 'keysender' to use this provider. This is the default provider. ```bash AUTOMATION_PROVIDER=keysender node build/index.js ``` -------------------------------- ### Basic MCP Client Structure Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Initializes the MCP client with necessary imports, an asynchronous exit stack for resource management, and an Anthropic client instance. ```python import asyncio from typing import Optional from contextlib import AsyncExitStack from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client from anthropic import Anthropic from dotenv import load_dotenv load_dotenv() # load environment variables from .env class MCPClient: def __init__(self): # Initialize session and client objects self.session: Optional[ClientSession] = None self.exit_stack = AsyncExitStack() self.anthropic = Anthropic() # methods will go here ``` -------------------------------- ### Implement Basic Tool Server (TypeScript) Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Set up an MCP server to handle tool requests, including defining available tools and their execution logic. Requires `ListToolsRequestSchema` and `CallToolRequestSchema`. ```typescript const server = new Server({ name: "example-server", version: "1.0.0" }, { capabilities: { tools: {} } }); // Define available tools server.setRequestHandler(ListToolsRequestSchema, async () => { return { tools: [{ name: "calculate_sum", description: "Add two numbers together", inputSchema: { type: "object", properties: { a: { type: "number" }, b: { type: "number" } }, required: ["a", "b"] } }] }; }); // Handle tool execution server.setRequestHandler(CallToolRequestSchema, async (request) => { if (request.params.name === "calculate_sum") { const { a, b } = request.params.arguments; return { content: [ { type: "text", text: String(a + b) } ] }; } throw new Error("Tool not found"); }); ``` -------------------------------- ### Run Chatbot Application Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Executes the chatbot application using the compiled JAR file or via Maven. The application starts an interactive chat session. ```bash ./mvnw clean install java -jar ./target/ai-mcp-brave-chatbot-0.0.1-SNAPSHOT.jar ``` ```bash ./mvnw spring-boot:run ``` -------------------------------- ### TypeScript Transport Interface Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Defines the interface for custom transports, outlining methods for starting, sending, and closing connections, along with error handling callbacks. ```typescript interface Transport { // Start processing messages start(): Promise; // Send a JSON-RPC message send(message: JSONRPCMessage): Promise; // Close the connection close(): Promise; // Callbacks onclose?: () => void; onerror?: (error: Error) => void; onmessage?: (message: JSONRPCMessage) => void; } ``` -------------------------------- ### Initialize and Run MCP Server Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Initializes and runs the MCP server using the 'stdio' transport. This is the main entry point for the server. ```python if __name__ == "__main__": # Initialize and run the server mcp.run(transport='stdio') ``` -------------------------------- ### Implement MCP tool for getting weather forecast Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Defines an MCP tool to retrieve the weather forecast for a specific geographic location using latitude and longitude. ```python @mcp.tool() async def get_forecast(latitude: float, longitude: float) -> str: """Get weather forecast for a location. Args: latitude: Latitude of the location longitude: Longitude of the location """ # First get the forecast grid endpoint ``` -------------------------------- ### Helper function for NWS API requests Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Makes asynchronous GET requests to the NWS API with specified headers and timeout. Includes basic error handling. ```python async def make_nws_request(url: str) -> dict[str, Any] | None: """Make a request to the NWS API with proper error handling.""" headers = { "User-Agent": USER_AGENT, "Accept": "application/geo+json" } async with httpx.AsyncClient() as client: try: response = await client.get(url, headers=headers, timeout=30.0) response.raise_for_status() return response.json() except Exception: return None ``` -------------------------------- ### Python Custom Transport Implementation Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Provides an example of implementing a custom transport using anyanyio for broader compatibility, including message processing and stream management. ```python @contextmanager async def create_transport( read_stream: MemoryObjectReceiveStream[JSONRPCMessage | Exception], write_stream: MemoryObjectSendStream[JSONRPCMessage] ): """ Transport interface for MCP. Args: read_stream: Stream to read incoming messages from write_stream: Stream to write outgoing messages to """ async with anyio.create_task_group() as tg: try: # Start processing messages tg.start_soon(lambda: process_messages(read_stream)) # Send messages async with write_stream: yield write_stream except Exception as exc: # Handle errors raise exc finally: # Clean up tg.cancel_scope.cancel() await write_stream.aclose() await read_stream.aclose() ``` -------------------------------- ### List and Retrieve Resources (Sync) Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Use the synchronous API to list available resources and retrieve their content using URI templates. Ensure the MCP client is initialized. ```java var resources = client.listResources(); resources.forEach(resource -> System.out.println(resource.getName())); var content = client.getResource("file", Map.of( "path", "/path/to/file.txt" )); ``` -------------------------------- ### Tool Definition: System Operations Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Example schema for a tool that executes shell commands. Ensure proper sanitization of command and arguments to prevent injection vulnerabilities. ```typescript { name: "execute_command", description: "Run a shell command", inputSchema: { type: "object", properties: { command: { type: "string" }, args: { type: "array", items: { type: "string" } } } } } ``` -------------------------------- ### Initialize MCP and Anthropic Client Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Sets up the necessary imports and instantiates the MCP client and Anthropic client with API key. ```typescript import { Anthropic } from "@anthropic-ai/sdk"; import { MessageParam, Tool, } from "@anthropic-ai/sdk/resources/messages/messages.mjs"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; import readline from "readline/promises"; import dotenv from "dotenv"; dotenv.config(); const ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY; if (!ANTHROPIC_API_KEY) { throw new Error("ANTHROPIC_API_KEY is not set"); } class MCPClient { private mcp: Client; private anthropic: Anthropic; private transport: StdioClientTransport | null = null; private tools: Tool[] = []; constructor() { this.anthropic = new Anthropic({ apiKey: ANTHROPIC_API_KEY, }); this.mcp = new Client({ name: "mcp-client-cli", version: "1.0.0" }); } // methods will go here } ``` -------------------------------- ### Run mcp-control with SSE transport Source: https://github.com/claude-did-this/mcpcontrol/blob/main/RELEASE_NOTES_v0.2.0.md Use this command to start the mcp-control service with Server-Sent Events (SSE) transport enabled. SSE is the recommended transport method. ```bash mcp-control --sse ``` -------------------------------- ### Configure Modular Providers via Environment Variables Source: https://github.com/claude-did-this/mcpcontrol/blob/main/src/providers/autohotkey/README.md Set individual environment variables for each automation module (keyboard, mouse, screen, clipboard) to use AutoHotkey. ```bash export AUTOMATION_KEYBOARD_PROVIDER=autohotkey export AUTOMATION_MOUSE_PROVIDER=autohotkey export AUTOMATION_SCREEN_PROVIDER=autohotkey export AUTOMATION_CLIPBOARD_PROVIDER=autohotkey ``` -------------------------------- ### Configure Local Launch with SSE Source: https://github.com/claude-did-this/mcpcontrol/blob/main/README.md Configures Claude to launch MCPControl locally with SSE transport. This is useful for local development and testing. ```json { "mcpServers": { "MCPControl": { "command": "mcp-control", "args": ["--sse"] } } } ``` -------------------------------- ### Run MCP Filesystem Server on Windows Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Manually run the MCP filesystem server from the command line on Windows. Ensure the paths provided are absolute. ```bash npx -y @modelcontextprotocol/server-filesystem C:\Users\username\Desktop C:\Users\username\Downloads ``` -------------------------------- ### SSE Endpoint Request Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/sse-transport.md Client initiates an SSE connection by sending a GET request to the /mcp/sse endpoint with the 'Accept: text/event-stream' header. Authentication is handled via a JWT query parameter. ```http GET /mcp/sse?auth=&v=2025-04-30 HTTP/1.1 Accept: text/event-stream ``` -------------------------------- ### Connect to MCP Server Source: https://github.com/claude-did-this/mcpcontrol/blob/main/docs/llms-full.txt Establishes a connection to an MCP server using its script path, handling both Python and Node.js servers. It initializes the session and lists available tools. ```python async def connect_to_server(self, server_script_path: str): """Connect to an MCP server Args: server_script_path: Path to the server script (.py or .js) """ is_python = server_script_path.endswith('.py') is_js = server_script_path.endswith('.js') if not (is_python or is_js): raise ValueError("Server script must be a .py or .js file") command = "python" if is_python else "node" server_params = StdioServerParameters( command=command, args=[server_script_path], env=None ) stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params)) self.stdio, self.write = stdio_transport self.session = await self.exit_stack.enter_async_context(ClientSession(self.stdio, self.write)) await self.session.initialize() # List available tools response = await self.session.list_tools() tools = response.tools print("\nConnected to server with tools:", [tool.name for tool in tools]) ```