### Installing npx Globally (Bash) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Command to install the npx package manager globally using npm, a prerequisite for the Java example setup. ```bash npm install -g npx ``` -------------------------------- ### Cloning and Navigating Spring AI Examples (Bash) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Commands to clone the Spring AI examples GitHub repository and navigate into the specific directory for the Brave Chatbot example. ```bash git clone https://github.com/spring-projects/spring-ai-examples.git cd model-context-protocol/brave-chatbot ``` -------------------------------- ### Installing uv Package Manager Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Installs the uv package manager, a fast Python package installer and resolver, which is used for environment setup and dependency management in this project. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` ```powershell powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" ``` -------------------------------- ### Implementing MCP Resource Handlers (Python) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Example implementation of MCP server handlers for listing and reading resources in Python. It uses decorators to define handlers for listing and reading resources and includes server setup and execution using `stdio_server`. ```python app = Server("example-server") @app.list_resources() async def list_resources() -> list[types.Resource]: return [ types.Resource( uri="file:///logs/app.log", name="Application Logs", mimeType="text/plain" ) ] @app.read_resource() async def read_resource(uri: AnyUrl) -> str: if str(uri) == "file:///logs/app.log": log_contents = await read_log_file() return log_contents raise ValueError("Resource not found") # Start server async with stdio_server() as streams: await app.run( streams[0], streams[1], app.create_initialization_options() ) ``` -------------------------------- ### Installing and Running Python MCP Server with pip Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Illustrates the traditional method of installing a Python-based MCP server using pip and then running it as a module. ```bash pip install mcp-server-git python -m mcp_server_git ``` -------------------------------- ### Demonstrating Server Path Usage (Bash) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Examples showing how to specify the server script path when running the client using `uv run`, including relative, absolute, and Windows-specific formats. ```bash # Relative path uv run client.py ./server/weather.py # Absolute path uv run client.py /Users/username/projects/mcp-server/weather.py # Windows path (either format works) uv run client.py C:/projects/mcp-server/weather.py uv run client.py C:\\projects\\mcp-server\\weather.py ``` -------------------------------- ### Example MCP Server Description Prompt Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt This snippet provides an example of how to describe the desired functionality of an MCP server to Claude, outlining its resources, tools, prompts, and external interactions. ```Description 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 ``` -------------------------------- ### Example MCP Client Roots Configuration (JSON) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Illustrates the JSON format used by an MCP client to suggest workspace roots to a server. It includes examples for a local file path (`uri` with `file://` scheme) and an API endpoint (`uri` with `https://` scheme), each with a descriptive `name`. ```JSON { "roots": [ { "uri": "file:///home/user/projects/frontend", "name": "Frontend Repository" }, { "uri": "https://api.example.com/v1", "name": "API Endpoint" } ] } ``` -------------------------------- ### Setting Up Project Environment with uv Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Creates a new project directory, initializes a uv environment, activates the virtual environment, installs necessary dependencies (mcp[cli] and httpx), and creates the main Python 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 ``` -------------------------------- ### Running TypeScript MCP Server with npx Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Demonstrates how to run a TypeScript-based MCP server directly using the npx command-line tool, which executes packages without explicit installation. ```bash npx -y @modelcontextprotocol/server-memory ``` -------------------------------- ### Setting Up Client Environment (Bash) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Provides bash commands using `uv` to create the project directory, set up and activate a virtual environment, install necessary Python packages (`mcp`, `anthropic`, `python-dotenv`), remove boilerplate files, and create the main client script file. ```bash # Create project directory uv init mcp-client cd mcp-client # Create virtual environment uv venv # Activate virtual environment # On Windows: .venv\Scripts\activate # On Unix or MacOS: source .venv/bin/activate # Install required packages uv add mcp anthropic python-dotenv # Remove boilerplate files rm hello.py # Create our main file touch client.py ``` -------------------------------- ### Setting up Project Directory and Dependencies - PowerShell Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Provides PowerShell commands for creating the project directory, navigating into it, initializing a new npm project, installing required dependencies (@modelcontextprotocol/sdk, zod, @types/node, typescript), and creating the source directory and index.ts file on Windows. ```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 ``` -------------------------------- ### Setting up Project Directory and Dependencies - Bash Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Provides bash commands for creating the project directory, navigating into it, initializing a new npm project, installing required dependencies (@modelcontextprotocol/sdk, zod, @types/node, typescript), and creating the source directory and index.ts file on MacOS/Linux. ```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 ``` -------------------------------- ### Verify Node.js Installation Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Command to run in the terminal (macOS/Linux) or command prompt (Windows) to check if Node.js is installed and display its version. Required for the Filesystem MCP Server to run. ```bash node --version ``` -------------------------------- ### Install via Smithery CLI (Bash) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/README.md Command to automatically install the GitHub Projects MCP Server using the Smithery CLI, specifically configured for the Claude client. ```bash npx -y @smithery/cli install taylor-lindores-reeves/mcp-github-projects --client claude ``` -------------------------------- ### Implementing MCP Server in TypeScript Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Provides a basic example of setting up an MCP server using the TypeScript SDK. It demonstrates server initialization with name and version, defining capabilities, setting a request handler for listing resources, and connecting the server using the StdioServerTransport. ```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); ``` -------------------------------- ### Checking Node.js and npm Versions (Bash) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Commands to verify the installed versions of Node.js and npm using the `--version` flag in a bash terminal. ```bash node --version npm --version ``` -------------------------------- ### Configure MCP Client (JSON) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/README.md Example JSON configuration snippet for an MCP client, detailing how to set up the GitHub Projects server with the correct command, arguments pointing to the built index.js file, and necessary environment variables. ```json { "mcpServers": { "GitHubProjects": { "command": "bun", "args": [ "/path/to/your/directory/mcp-github-projects-main/build/index.js" ], "env": { "GITHUB_TOKEN": "your_github_personal_access_token", "GITHUB_OWNER": "your_github_username_or_org" } } } } ``` -------------------------------- ### Install Dependencies (Bun) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/README.md Command to install the project's dependencies using the Bun package manager, required before building or running the server. ```bash bun install ``` -------------------------------- ### Accessing Resources with MCP Java SDK Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Demonstrates how to list available resources and retrieve their content using the MCP client's resource access methods. Examples are provided for both synchronous and asynchronous API styles. ```java // List available resources and their names var resources = client.listResources(); resources.forEach(resource -> System.out.println(resource.getName())); // Retrieve resource content using a URI template var content = client.getResource("file", Map.of( "path", "/path/to/file.txt" )); ``` ```java // List available resources asynchronously client.listResources() .doOnNext(resources -> resources.forEach(resource -> System.out.println(resource.getName()))) .subscribe(); // Retrieve resource content asynchronously client.getResource("file", Map.of( "path", "/path/to/file.txt" )) .subscribe(); ``` -------------------------------- ### Install NPM Globally Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Command to install or update the Node Package Manager (NPM) globally on the system. This is required for the `npx` command used to run MCP servers. ```bash npm install -g npm ``` -------------------------------- ### Opening Claude Desktop Config (MacOS/Linux Bash) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Uses the `code` command (assuming VS Code is installed and in the PATH) to open the Claude for Desktop configuration file on MacOS or Linux systems. ```bash code ~/Library/Application\ Support/Claude/claude_desktop_config.json ``` -------------------------------- ### Inspecting PyPi Server Package (Bash) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Shows how to use the MCP Inspector to run and interact with an MCP server installed as a PyPi package using `uvx`. This is useful for testing Python-based MCP servers. ```Bash npx @modelcontextprotocol/inspector uvx ``` ```Bash npx @modelcontextprotocol/inspector uvx mcp-server-git --repository ~/code/mcp/servers.git ``` -------------------------------- ### Interacting with Prompt System using MCP Java SDK Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Illustrates how to discover available prompt templates and execute them with custom parameters using the MCP client's prompt system methods. Examples cover both synchronous and asynchronous API usage. ```java // List available prompt templates var prompts = client.listPrompts(); prompts.forEach(prompt -> System.out.println(prompt.getName())); // Execute a prompt template with parameters var response = client.executePrompt("echo", Map.of( "text", "Hello, World!" )); ``` ```java // List available prompt templates asynchronously client.listPrompts() .doOnNext(prompts -> prompts.forEach(prompt -> System.out.println(prompt.getName()))) .subscribe(); // Execute a prompt template asynchronously client.executePrompt("echo", Map.of( "text", "Hello, World!" )) .subscribe(); ``` -------------------------------- ### Running Spring Boot Application (Bash) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Command to run the Spring Boot application using the Maven wrapper plugin, starting the embedded web server and making the application accessible. ```bash ./mvnw spring-boot:run ``` -------------------------------- ### Implementing a Multi-step Workflow Prompt (TypeScript) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Provides a TypeScript example of how a prompt can be implemented with an asynchronous function (`getMessages`) to generate messages dynamically, enabling multi-step conversational workflows. ```typescript const debugWorkflow = { name: "debug-error", async getMessages(error: string) { return [ { role: "user", content: { type: "text", text: `Here's an error I'm seeing: ${error}` } }, { role: "assistant", content: { type: "text", text: "I'll help analyze this error. What have you tried so far?" } }, { role: "user", content: { type: "text", text: "I've tried restarting the service, but the error persists." } } ]; } }; ``` -------------------------------- ### Inspecting NPM Server Package (Bash) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Illustrates how to use the MCP Inspector to run and interact with an MCP server installed as an NPM package. The `-y` flag automatically confirms installation prompts. ```Bash npx -y @modelcontextprotocol/inspector npx ``` ```Bash npx -y @modelcontextprotocol/inspector npx server-postgres postgres://127.0.0.1/testdb ``` -------------------------------- ### Opening Claude Desktop Config (Windows PowerShell) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Uses the `code` command (assuming VS Code is installed and in the PATH) to open the Claude for Desktop configuration file on Windows systems using the `$env:AppData` environment variable. ```powershell code $env:AppData\Claude\claude_desktop_config.json ``` -------------------------------- ### Configuring MCP Servers in Claude Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Provides an example JSON configuration object used to integrate and define multiple MCP servers within the Claude environment, specifying commands, arguments, and environment variables. ```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": "" } } } } ``` -------------------------------- ### Example MCP Sampling Request - JSON Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Illustrates a sample JSON payload for making a sampling request using the 'sampling/createMessage' method, specifying 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 } } ``` -------------------------------- ### Opening Claude Config - MacOS/Linux Bash Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Provides a bash command to open the Claude for Desktop configuration file located at ~/Library/Application Support/Claude/claude_desktop_config.json using the code command (assuming VS Code is installed and in the PATH). ```bash code ~/Library/Application\ Support/Claude/claude_desktop_config.json ``` -------------------------------- ### Running MCP Inspector (Basic Bash) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Provides the basic command structure for running the MCP Inspector tool directly via `npx` without requiring a global installation. This command is used to interact with MCP servers. ```Bash npx @modelcontextprotocol/inspector ``` ```Bash npx @modelcontextprotocol/inspector ``` -------------------------------- ### Opening Claude Config - Windows Powershell Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Provides a Powershell command to open the Claude for Desktop configuration file located at %AppData%\Claude\claude_desktop_config.json using the code command (assuming VS Code is installed and in the PATH). ```powershell code $env:AppData\Claude\claude_desktop_config.json ``` -------------------------------- ### Example MCP Root URIs Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Examples of valid URIs that can be used as roots in the Model Context Protocol (MCP). Roots define the boundaries where an MCP server should operate, typically representing file system paths or web URLs. ```text file:///home/user/projects/myapp https://api.example.com/v1 ``` -------------------------------- ### Configure Environment Variables (.env) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/README.md Example content for the `.env` file, specifying the required GitHub Personal Access Token and the GitHub owner (username or organization) for server authentication. ```env GITHUB_TOKEN=your_github_personal_access_token GITHUB_OWNER=your_github_username ``` -------------------------------- ### Clone Repository (Bash) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/README.md Commands to clone the GitHub repository containing the MCP server code and navigate into the project directory for manual installation. ```bash git clone https://github.com/taylor-lindores-reeves/mcp-github-projects.git cd mcp-github-projects ``` -------------------------------- ### Configure APPDATA Environment Variable Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Example JSON configuration for `claude_desktop_config.json` showing how to explicitly set the `APPDATA` environment variable within the `env` key for a server definition to resolve `ENOENT` errors on Windows. ```json { "brave-search": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-brave-search"], "env": { "APPDATA": "C:\\Users\\user\\AppData\\Roaming\\", "BRAVE_API_KEY": "..." } } } ``` -------------------------------- ### Implementing MCP Resource Handlers (TypeScript) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Example implementation of MCP server handlers for listing and reading resources in TypeScript. It sets up a server with resource capabilities and defines handlers for `ListResourcesRequestSchema` and `ReadResourceRequestSchema` to serve a specific log file. ```typescript const server = new Server({ name: "example-server", version: "1.0.0" }, { capabilities: { resources: {} } }); // List available resources server.setRequestHandler(ListResourcesRequestSchema, async () => { return { resources: [ { uri: "file:///logs/app.log", name: "Application Logs", mimeType: "text/plain" } ] }; }); // Read resource contents server.setRequestHandler(ReadResourceRequestSchema, async (request) => { const uri = request.params.uri; if (uri === "file:///logs/app.log") { const logContents = await readLogFile(); return { contents: [ { uri, mimeType: "text/plain", text: logContents } ] }; } throw new Error("Resource not found"); }); ``` -------------------------------- ### Running MCP Server Main Function - TypeScript Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Defines the main asynchronous function to start the MCP server. It sets up a StdioServerTransport, connects the server, logs a message, and includes error handling for the main execution. ```typescript async function main() { const transport = new StdioServerTransport(); await server.connect(transport); console.error("Weather MCP Server running on stdio"); } main().catch((error) => { console.error("Fatal error in main():", error); process.exit(1); }); ``` -------------------------------- ### Define System Operation Tool Schema - TypeScript Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Provides an example JSON Schema definition for an MCP tool designed to execute system commands, specifying parameters for the command string and optional arguments. ```typescript { name: "execute_command", description: "Run a shell command", inputSchema: { type: "object", properties: { command: { type: "string" }, args: { type: "array", items: { type: "string" } } } } } ``` -------------------------------- ### Running the MCP Client (Bash) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt These commands show how to execute the MCP client script using `uv run`. The first example runs the client with a Python server script, and the second runs it with a Node.js server script (compiled JavaScript). The client requires the path to the server script as a command-line argument. ```bash uv run client.py path/to/server.py # python server uv run client.py path/to/build/index.js # node server ``` -------------------------------- ### Execute Tools Sync API (Java) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Provides examples of using the synchronous API methods on the client to interact with server-side tools. `listTools()` retrieves available tools, and `callTool()` executes a tool by name with a map of parameters, returning the result directly. ```java // List available tools and their names var tools = client.listTools(); tools.forEach(tool -> System.out.println(tool.getName())); // Execute a tool with parameters var result = client.callTool("calculator", Map.of( "operation", "add", "a", 1, "b", 2 )); ``` -------------------------------- ### Stdio Transport Initialization (Python Server) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Initializes a server application using the stdio transport in Python. This setup is designed for communication over standard input and output streams, typically for local or command-line interactions. The code creates a Server instance and runs it using streams obtained from the stdio_server context manager. ```Python app = Server("example-server") async with stdio_server() as streams: await app.run( streams[0], streams[1], app.create_initialization_options() ) ``` -------------------------------- ### Implement Prompts in MCP Server (Python) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt This snippet provides a Python example for implementing prompts in an MCP server. It shows how to define prompts using mcp.types.Prompt and mcp.types.PromptArgument and how to use the @app.list_prompts() and @app.get_prompt() decorators to handle incoming requests for listing and retrieving prompts, generating appropriate messages based on the request. ```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", text=f"Explain how this {language} code works:\n\n{code}" ) ) ] ) raise ValueError("Prompt implementation not found") ``` -------------------------------- ### Implementing Transport Error Handling in Python Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt This Python context manager provides a more comprehensive example of transport implementation using `anyio`, including setting up streams, handling messages within a task group, and incorporating error handling at multiple levels (message handling, transport yield, initialization). ```python @contextmanager async def example_transport(scope: Scope, receive: Receive, send: Send): try: # Create streams for bidirectional communication read_stream_writer, read_stream = anyio.create_memory_object_stream(0) write_stream, write_stream_reader = anyio.create_memory_object_stream(0) async def message_handler(): try: async with read_stream_writer: # Message handling logic pass except Exception as exc: logger.error(f"Failed to handle message: {exc}") raise exc async with anyio.create_task_group() as tg: tg.start_soon(message_handler) try: # Yield streams for communication yield read_stream, write_stream except Exception as exc: logger.error(f"Transport error: {exc}") raise exc finally: tg.cancel_scope.cancel() await write_stream.aclose() await read_stream.aclose() except Exception as exc: logger.error(f"Failed to initialize transport: {exc}") raise exc ``` -------------------------------- ### Implementing MCP Tool get_forecast (Partial) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Starts the definition of an asynchronous MCP tool function `get_forecast` using the `@mcp.tool()` decorator. This tool is intended to get the weather forecast for a specific geographic location provided by latitude and longitude coordinates. The snippet shows the function signature and docstring. ```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 ``` -------------------------------- ### Initializing and Running MCP Server (Python) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Standard Python entry point (`if __name__ == "__main__":`) to initialize and run the MCP server using the `mcp.run()` function with the 'stdio' transport. ```python if __name__ == "__main__": # Initialize and run the server mcp.run(transport='stdio') ``` -------------------------------- ### Build Client Capabilities (Java) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Demonstrates how to build a `ClientCapabilities` object using its builder pattern. This allows enabling specific features like filesystem roots support (`roots(true)`) and LLM sampling support (`sampling()`) for the client instance. ```java var capabilities = ClientCapabilities.builder() .roots(true) // Enable filesystem roots support with list changes notifications .sampling() // Enable LLM sampling support .build(); ``` -------------------------------- ### Implement MCP Server with Tool Handling Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Demonstrates how to set up an MCP server, register a 'calculate_sum' tool, and handle both the listing of available tools and the execution of a specific tool request. ```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"); }); ``` ```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}") ``` -------------------------------- ### Configuring ServerCapabilities Builder in Java Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Demonstrates how to use the `ServerCapabilities.builder()` to configure various server features such as resource, tool, prompt, and logging support. Each method on the builder enables or customizes a specific capability. ```java var capabilities = ServerCapabilities.builder() .resources(false, true) // Resource support with list changes notifications .tools(true) // Tool support with list changes notifications .prompts(true) // Prompt support with list changes notifications .logging() // Enable logging support (enabled by default with loging level INFO) .build(); ``` -------------------------------- ### Importing Dependencies and Initializing MCP Server - TypeScript Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Imports necessary classes from the Model Context Protocol SDK (McpServer, StdioServerTransport) and Zod, defines constants for the NWS API base URL and User Agent, and initializes a new McpServer instance with a name and version. ```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", }); ``` -------------------------------- ### Creating and Using McpClient (Java) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Demonstrates how to create a synchronous McpClient using the STDIO transport, initialize it, list available tools, call the "getWeatherForecastByLocation" and "getAlerts" tools, and gracefully close the client. ```Java var stdioParams = ServerParameters.builder("java") .args("-jar", "/ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar") .build(); var stdioTransport = new StdioClientTransport(stdioParams); var mcpClient = McpClient.sync(stdioTransport).build(); mcpClient.initialize(); ListToolsResult toolsList = mcpClient.listTools(); CallToolResult weather = mcpClient.callTool( new CallToolRequest("getWeatherForecastByLocation", Map.of("latitude", "47.6062", "longitude", "-122.3321"))); CallToolResult alert = mcpClient.callTool( new CallToolRequest("getAlerts", Map.of("state", "NY"))); mcpClient.closeGracefully(); ``` -------------------------------- ### Implementing Sync MCP Server in Java Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt This snippet demonstrates how to create, configure, and manage a synchronous MCP server instance. It shows how to set server information, define capabilities, register tools, resources, and prompts, send logging notifications, and properly close the server. ```java // Create a server with custom configuration 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(); // Register tools, resources, and prompts syncServer.addTool(syncToolRegistration); syncServer.addResource(syncResourceRegistration); syncServer.addPrompt(syncPromptRegistration); // Send logging notifications syncServer.loggingNotification(LoggingMessageNotification.builder() .level(LoggingLevel.INFO) .logger("custom-logger") .data("Server initialized") .build()); // Close the server when done syncServer.close(); ``` -------------------------------- ### Defining Main Execution Logic (Python) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt This is the main entry point for the client script. It checks for command-line arguments (the server script path), initializes the `MCPClient`, connects to the specified server, runs the interactive chat loop, and ensures that the `cleanup` function is called upon exit, even if errors occur, using a `finally` block. ```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()) ``` -------------------------------- ### Add MCP Client Boot Starter Dependency (Maven) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Add this Maven dependency to your project's pom.xml file to include the Spring AI MCP Client Spring Boot Starter, enabling auto-configuration for MCP clients. ```XML org.springframework.ai spring-ai-mcp-client-spring-boot-starter ``` -------------------------------- ### Adding Anthropic API Key to .env Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Shows the format for adding your Anthropic API key to the newly created `.env` file. Replace `` with your actual API key obtained from the Anthropic console. ```text ANTHROPIC_API_KEY= ``` -------------------------------- ### Opening Claude Desktop Config (MacOS/Linux Bash) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Command to open the Claude Desktop configuration file claude_desktop_config.json using VS Code on MacOS or Linux. ```Bash code ~/Library/Application\ Support/Claude/claude_desktop_config.json ``` -------------------------------- ### Implementing MCP Server in Python Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Shows a basic implementation of an MCP server in Python. It initializes the server, defines an asynchronous handler for listing resources using a decorator, and runs the server using the stdio_server context manager for standard I/O communication. ```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) ``` -------------------------------- ### Using MCP Sync Client in Java Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Demonstrates how to create, configure, initialize, and interact with an MCP server using the synchronous Java client API. Covers capabilities, timeouts, tool calls, resource access, prompt usage, and roots management. ```Java // Create a sync client with custom configuration McpSyncClient client = McpClient.sync(transport) .requestTimeout(Duration.ofSeconds(10)) .capabilities(ClientCapabilities.builder() .roots(true) // Enable roots capability .sampling() // Enable sampling capability .build()) .sampling(request -> new CreateMessageResult(response)) .build(); // Initialize connection client.initialize(); // List available tools ListToolsResult tools = client.listTools(); // Call a tool CallToolResult result = client.callTool( new CallToolRequest("calculator", Map.of("operation", "add", "a", 2, "b", 3)) ); // List and read resources ListResourcesResult resources = client.listResources(); ReadResourceResult resource = client.readResource( new ReadResourceRequest("resource://uri") ); // List and use prompts ListPromptsResult prompts = client.listPrompts(); GetPromptResult prompt = client.getPrompt( new GetPromptRequest("greeting", Map.of("name", "Spring")) ); // Add/remove roots client.addRoot(new Root("file:///path", "description")); client.removeRoot("file:///path"); // Close client client.closeGracefully(); ``` -------------------------------- ### Building the MCP Server (Bash) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Command to build the Spring Boot application using Maven Wrapper, producing an executable JAR file in the target directory. ```Bash ./mvnw clean install ``` -------------------------------- ### Define API Integration Tool Schema - TypeScript Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Provides an example JSON Schema definition for an MCP tool that wraps an external API, specifically for creating a GitHub issue with parameters for title, body, and labels. ```typescript { name: "github_create_issue", description: "Create a GitHub issue", inputSchema: { type: "object", properties: { title: { type: "string" }, body: { type: "string" }, labels: { type: "array", items: { type: "string" } } } } } ``` -------------------------------- ### Build and Run Spring Boot Application (Maven JAR) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Provides command-line instructions to build the Spring Boot application into an executable JAR using Maven and then run the generated JAR file. ```bash ./mvnw clean install java -jar ./target/ai-mcp-brave-chatbot-0.0.1-SNAPSHOT.jar ``` -------------------------------- ### Defining Transport Interface in TypeScript Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt This TypeScript interface defines the contract that any custom MCP transport implementation must adhere to. It includes methods for starting, sending messages, closing the connection, and optional callbacks for connection events. ```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; } ``` -------------------------------- ### Opening Claude Desktop Config (Windows PowerShell) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Command to open the Claude Desktop configuration file claude_desktop_config.json using VS Code on Windows. ```PowerShell code $env:AppData\Claude\claude_desktop_config.json ``` -------------------------------- ### Define Data Processing Tool Schema - TypeScript Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Provides an example JSON Schema definition for an MCP tool designed for data processing, allowing analysis of a CSV file with specified operations like sum, average, or count. ```typescript { name: "analyze_csv", description: "Analyze a CSV file", inputSchema: { type: "object", properties: { filepath: { type: "string" }, operations: { type: "array", items: { enum: ["sum", "average", "count"] } } } } } ``` -------------------------------- ### Creating .env File (Bash) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Provides the bash command to create an empty `.env` file in the project root, which will be used to store sensitive information like API keys. ```bash # Create .env file touch .env ``` -------------------------------- ### Importing Packages and Initializing FastMCP Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Imports required Python libraries including typing, httpx for making HTTP requests, and FastMCP from the mcp.server module. It then initializes a FastMCP server instance named 'mcp' with the name 'weather' and defines constants for the NWS API base URL and a User-Agent string. ```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" ``` -------------------------------- ### Manually Run Filesystem Server (Windows) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Command to manually run the MCP filesystem server on Windows to test for errors, replacing the placeholder paths with the desired absolute paths. ```bash npx -y @modelcontextprotocol/server-filesystem C:\Users\username\Desktop C:\Users\username\Downloads ``` -------------------------------- ### Using MCP Async Client in Java Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Illustrates how to create, configure, initialize, and interact with an MCP server using the asynchronous Java client API based on reactive programming (Mono). Shows configuration, capabilities, change consumers, and chaining asynchronous operations for tools, resources, prompts, and roots. ```Java // Create an async client with custom configuration McpAsyncClient client = McpClient.async(transport) .requestTimeout(Duration.ofSeconds(10)) .capabilities(ClientCapabilities.builder() .roots(true) // Enable roots capability .sampling() // Enable sampling capability .build()) .sampling(request -> Mono.just(new CreateMessageResult(response))) .toolsChangeConsumer(tools -> Mono.fromRunnable(() -> { logger.info("Tools updated: {}", tools); })) .resourcesChangeConsumer(resources -> Mono.fromRunnable(() -> { logger.info("Resources updated: {}", resources); })) .promptsChangeConsumer(prompts -> Mono.fromRunnable(() -> { logger.info("Prompts updated: {}", prompts); })) .build(); // Initialize connection and use features client.initialize() .flatMap(initResult -> client.listTools()) .flatMap(tools -> { return client.callTool(new CallToolRequest( "calculator", Map.of("operation", "add", "a", 2, "b", 3) )); }) .flatMap(result -> { return client.listResources() .flatMap(resources -> client.readResource(new ReadResourceRequest("resource://uri")) ); }) .flatMap(resource -> { return client.listPrompts() .flatMap(prompts -> client.getPrompt(new GetPromptRequest( "greeting", Map.of("name", "Spring") )) ); }) .flatMap(prompt -> { return client.addRoot(new Root("file:///path", "description")) .then(client.removeRoot("file:///path")); }) .doFinally(signalType -> { client.closeGracefully().subscribe(); }) .subscribe(); ``` -------------------------------- ### SSE Transport Implementation (Python Server) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Implements an SSE server using the Starlette framework in Python. This setup supports server-to-client streaming and handles client messages via HTTP POST requests. The code defines routes for SSE connections and message handling, connecting the server instance to the SseServerTransport. ```Python from mcp.server.sse import SseServerTransport from starlette.applications import Starlette from starlette.routing import Route app = Server("example-server") sse = SseServerTransport("/messages") async def handle_sse(scope, receive, send): async with sse.connect_sse(scope, receive, send) as streams: await app.run(streams[0], streams[1], app.create_initialization_options()) async def handle_messages(scope, receive, send): await sse.handle_post_message(scope, receive, send) starlette_app = Starlette( routes=[ Route("/sse", endpoint=handle_sse), Route("/messages", endpoint=handle_messages, methods=["POST"]), ] ) ``` -------------------------------- ### Connecting to MCP Server (Python) Source: https://github.com/taylor-lindores-reeves/mcp-github-projects/blob/main/llms-full.txt Implements the `connect_to_server` asynchronous method within the `MCPClient` class. This method takes the path to a server script (.py or .js), determines the correct command (`python` or `node`), sets up stdio server parameters, establishes a stdio transport connection, creates and initializes an MCP `ClientSession`, and lists the tools available from the connected server. ```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]) ```