### Define main entry point Source: https://modelcontextprotocol.info/docs/tutorials/building-a-client Initializes the client, connects to the server, and starts the chat loop. ```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 asyncio.run(main()) ``` -------------------------------- ### Initialize TypeScript project Source: https://modelcontextprotocol.info/docs/quickstart/quickstart Commands to create the project directory and install necessary dependencies. ```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 ``` ```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 ``` -------------------------------- ### Initialize MCP Client Project Source: https://modelcontextprotocol.info/docs/development/build-client Commands to set up the project directory, virtual environment, and install necessary dependencies. ```bash # Create project directory uv init mcp-client cd mcp-client # Create virtual environment uv venv # Activate virtual environment (macOS/Linux) source .venv/bin/activate # Install dependencies uv add mcp anthropic python-dotenv # Cleanup boilerplate and create main file rm main.py touch client.py ``` -------------------------------- ### Initializing the server instance Source: https://modelcontextprotocol.info/docs/quickstart/quickstart Define the server name and configuration constants before starting the application. ```python NWS_API_BASE = "https://api.weather.gov" USER_AGENT = "weather-app/1.0" server = Server("weather") ``` -------------------------------- ### Initialize Python Project Source: https://modelcontextprotocol.info/docs/quickstart/client Commands to initialize a new project, set up a virtual environment, and install necessary dependencies. ```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 ``` -------------------------------- ### Specify Server Paths Source: https://modelcontextprotocol.info/docs/tutorials/building-a-client-node Examples of providing relative, absolute, and Windows-specific paths to the client script. ```bash # Relative path node build/client.js ./server/weather.js # Absolute path node build/client.js /Users/username/projects/mcp-server/weather.js # Windows path (either format works) node build/client.js C:/projects/mcp-server/weather.js node build/client.js C:\\projects\\mcp-server\\weather.js ``` -------------------------------- ### Initialize Node.js Project Source: https://modelcontextprotocol.info/docs/tutorials/building-a-client-node Commands to create the project directory, initialize npm, install required dependencies, and set up the TypeScript configuration. ```bash # Create project directory mkdir mcp-client cd mcp-client # Initialize npm project npm init -y # Install dependencies npm install @modelcontextprotocol/sdk @anthropic-ai/sdk dotenv npm install -D typescript @types/node # Create TypeScript config npx tsc --init # Create necessary files mkdir src touch src/client.ts touch .env ``` -------------------------------- ### Initialize MCP Server Project Source: https://modelcontextprotocol.info/docs/learning-path Commands to create a directory, initialize a Node.js project, and install the required MCP TypeScript SDK. ```bash # Create project folder mkdir my-first-mcp-server cd my-first-mcp-server # Initialize Node.js project npm init -y # Install MCP SDK npm install @modelcontextprotocol/sdk-typescript ``` -------------------------------- ### Implement MCP Server with Java SDK Source: https://modelcontextprotocol.info/docs/sdk/java/mcp-server Examples for configuring and managing MCP servers using either synchronous or asynchronous APIs. ```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(); ``` ```java // Create an async server with custom configuration 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(); // Register tools, resources, and prompts 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(); // Send logging notifications asyncServer.loggingNotification(LoggingMessageNotification.builder() .level(LoggingLevel.INFO) .logger("custom-logger") .data("Server initialized") .build()); // Close the server when done asyncServer.close() .doOnSuccess(v -> logger.info("Server closed")) .subscribe(); ``` -------------------------------- ### Configure MCP Client Transports Source: https://modelcontextprotocol.info/docs/sdk/java/mcp-client Examples for initializing different transport layers for MCP communication. ```java ServerParameters params = ServerParameters.builder("npx") .args("-y", "@modelcontextprotocol/server-everything", "dir") .build(); McpTransport transport = new StdioClientTransport(params); ``` ```java McpTransport transport = new HttpClientSseClientTransport("http://your-mcp-server"); ``` ```java WebClient.Builder webClientBuilder = WebClient.builder() .baseUrl("http://your-mcp-server"); McpTransport transport = new WebFluxSseClientTransport(webClientBuilder); ``` -------------------------------- ### Build the MCP Server Source: https://modelcontextprotocol.info/docs/quickstart/server Uses Maven to clean and install the project, generating the executable JAR file. ```bash ./mvnw clean install ``` -------------------------------- ### Install uv package manager Source: https://modelcontextprotocol.info/docs/quickstart/quickstart Use these commands to install the uv tool for managing Python environments and dependencies. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` ```powershell powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" ``` -------------------------------- ### Prototype an MCP Server with TypeScript Source: https://modelcontextprotocol.info/docs/faqs A quick-start guide to initializing a project, creating a basic server, and testing it using the TypeScript SDK. ```bash # 1. Initialize project npm init -y npm install @modelcontextprotocol/sdk-typescript # 2. Create basic server cat > server.ts << 'EOF' import { Server } from '@modelcontextprotocol/sdk-typescript'; const server = new Server({ name: 'my-prototype', version: '1.0.0' }); server.tool('hello', 'Say hello', { name: { type: 'string' } }, async (args) => { return `Hello, ${args.name}!`; }); server.start(); EOF # 3. Test immediately npx tsx server.ts ``` -------------------------------- ### Configure MCP Server Paths Source: https://modelcontextprotocol.info/docs/quickstart/client Examples of valid relative, absolute, and Windows-specific paths for executing MCP server scripts. ```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 (both formats work) uv run client.py C:/projects/mcp-server/weather.py uv run client.py C:\\projects\\mcp-server\\weather.py ``` -------------------------------- ### Verify Node.js Installation Source: https://modelcontextprotocol.info/docs/quickstart/user Command to check if Node.js is installed on your system. ```bash node --version ``` -------------------------------- ### Define Root URIs Source: https://modelcontextprotocol.info/docs/concepts/roots Example of URI formats used to define root boundaries. ```text file:///home/user/projects/myapp https://api.example.com/v1 ``` -------------------------------- ### High-throughput deployment configuration Source: https://modelcontextprotocol.info/docs/faqs Example configuration for scaling MCP servers in a production environment using load balancing and caching. ```yaml deployment: servers: 3-5 instances load_balancer: nginx/haproxy caching: Redis for frequent queries monitoring: Prometheus + Grafana rate_limiting: per-client quotas ``` -------------------------------- ### Initialize MCP Client Class Source: https://modelcontextprotocol.info/docs/tutorials/building-a-client-node Basic setup for the MCP client class in TypeScript, including necessary imports and constructor initialization. ```typescript import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; import Anthropic from "@anthropic-ai/sdk"; import dotenv from "dotenv"; import { Tool } from "@anthropic-ai/sdk/resources/messages.js"; import { CallToolResultSchema, ListToolsResultSchema, } from "@modelcontextprotocol/sdk/types.js"; import * as readline from "node:readline"; dotenv.config(); interface MCPClientConfig { name?: string; version?: string; } class MCPClient { private client: Client | null = null; private anthropic: Anthropic; private transport: StdioClientTransport | null = null; constructor(config: MCPClientConfig = {}) { this.anthropic = new Anthropic(); } // Methods will go here } ``` -------------------------------- ### Evaluate Python MCP Servers Source: https://modelcontextprotocol.info/docs/examples Run Python-based MCP servers using either the recommended uvx tool or traditional pip installation. ```bash # Modern Python approach (recommended) uvx mcp-server-git # Traditional approach pip install mcp-server-git python -m mcp_server_git ``` -------------------------------- ### Initialize project structure Source: https://modelcontextprotocol.info/docs/quickstart/quickstart Commands to create the project directory, virtual environment, and necessary source files. ```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 httpx # Remove template file rm hello.py # Create our files mkdir -p src/weather touch src/weather/__init__.py touch src/weather/server.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 httpx # Clean up boilerplate code rm hello.py # Create our files md src md src\weather new-item src\weather\__init__.py new-item src\weather\server.py ``` -------------------------------- ### Requesting sampling from a client Source: https://modelcontextprotocol.info/docs/concepts/sampling Example of a sampling/createMessage request payload. ```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 } } ``` -------------------------------- ### Define package entry point Source: https://modelcontextprotocol.info/docs/quickstart/quickstart Implement the main entry point in __init__.py to run the server. ```python from . import server import asyncio def main(): """Main entry point for the package.""" asyncio.run(server.main()) # Optionally expose other important items at package level __all__ = ['main', 'server'] ``` -------------------------------- ### Define main entry point Source: https://modelcontextprotocol.info/docs/tutorials/building-a-client-node Initializes the client and connects to the server using command-line arguments. Ensures proper cleanup on failure. ```typescript // Main execution async function main() { if (process.argv.length < 3) { console.log("Usage: ts-node client.ts "); process.exit(1); } const client = new MCPClient(); try { await client.connectToServer(process.argv[2]); await client.chatLoop(); } catch (error) { console.error("Error:", error); await client.cleanup(); process.exit(1); } } // Run main if this is the main module if (import.meta.url === new URL(process.argv[1], "file:").href) { main(); } export default MCPClient; ``` -------------------------------- ### Main entry point for MCP client Source: https://modelcontextprotocol.info/docs/quickstart/client Initializes the client, connects to the server, and executes the chat loop. ```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 asyncio.run(main()) ``` -------------------------------- ### Implement SSE Transport Source: https://modelcontextprotocol.info/docs/concepts/transports Examples for connecting MCP clients and servers using Server-Sent Events over HTTP. ```typescript import express from "express"; const app = express(); const server = new Server({ name: "example-server", version: "1.0.0" }, { capabilities: {} }); let transport: SSEServerTransport | null = null; app.get("/sse", (req, res) => { transport = new SSEServerTransport("/messages", res); server.connect(transport); }); app.post("/messages", (req, res) => { if (transport) { transport.handlePostMessage(req, res); } }); app.listen(3000); ``` ```typescript const client = new Client({ name: "example-client", version: "1.0.0" }, { capabilities: {} }); const transport = new SSEClientTransport( new URL("http://localhost:3000/sse") ); await client.connect(transport); ``` ```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"]), ] ) ``` ```python async with sse_client("http://localhost:8000/sse") as streams: async with ClientSession(streams[0], streams[1]) as session: await session.initialize() ``` -------------------------------- ### Implement Stdio Transport Source: https://modelcontextprotocol.info/docs/concepts/transports Examples for connecting MCP clients and servers via standard input/output streams. ```typescript const server = new Server({ name: "example-server", version: "1.0.0" }, { capabilities: {} }); const transport = new StdioServerTransport(); await server.connect(transport); ``` ```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 app = Server("example-server") async with stdio_server() as streams: await app.run( streams[0], streams[1], app.create_initialization_options() ) ``` ```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() ``` -------------------------------- ### Configure package.json Source: https://modelcontextprotocol.info/docs/tutorials/building-a-client-node Update the package.json file to support ES modules and define build and start scripts. ```json { "type": "module", "scripts": { "build": "tsc", "start": "node build/client.js" } } ``` -------------------------------- ### Run the MCP Server Source: https://modelcontextprotocol.info/docs/quickstart/quickstart Initializes the server with StdioServerTransport and handles startup errors. ```typescript // Start the server 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); }); ``` -------------------------------- ### Initializing server instance and schemas Source: https://modelcontextprotocol.info/docs/quickstart/quickstart Define API constants, validation schemas, and the server instance with tool capabilities. ```typescript const NWS_API_BASE = "https://api.weather.gov"; const USER_AGENT = "weather-app/1.0"; // Define Zod schemas for validation const AlertsArgumentsSchema = z.object({ state: z.string().length(2), }); const ForecastArgumentsSchema = z.object({ latitude: z.number().min(-90).max(90), longitude: z.number().min(-180).max(180), }); // Create server instance const server = new Server( { name: "weather", version: "1.0.0", }, { capabilities: { tools: {}, }, } ); ``` -------------------------------- ### Initialize and use a synchronous MCP client Source: https://modelcontextprotocol.info/docs/sdk/java/mcp-client Configures a synchronous client with custom timeouts and capabilities, then demonstrates tool listing and execution. ```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)) ); ``` -------------------------------- ### Execute MCP Tools in Java Source: https://modelcontextprotocol.info/docs/sdk/java/mcp-client Demonstrates listing and executing tools using synchronous and asynchronous patterns. ```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 )); ``` ```java // List available tools asynchronously client.listTools() .doOnNext(tools -> tools.forEach(tool -> System.out.println(tool.getName()))) .subscribe(); // Execute a tool asynchronously client.callTool("calculator", Map.of( "operation", "add", "a", 1, "b", 2 )) .subscribe(); ``` -------------------------------- ### Configure Environment Variables Source: https://modelcontextprotocol.info/docs/quickstart/client Commands to create a .env file, add an API key, and update .gitignore. ```bash # Create .env file touch .env ``` ```bash ANTHROPIC_API_KEY= ``` ```bash echo ".env" >> .gitignore ``` -------------------------------- ### Initialize FastMCP Server Source: https://modelcontextprotocol.info/docs/quickstart/server Imports necessary libraries and initializes the FastMCP instance with basic configuration constants. ```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" ``` -------------------------------- ### Run the MCP server Source: https://modelcontextprotocol.info/docs/quickstart/server Initializes the stdio transport and connects the server instance. ```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); }); ``` -------------------------------- ### Run the MCP Server Source: https://modelcontextprotocol.info/docs/quickstart/server Initializes the server instance using the stdio transport protocol. ```python if __name__ == "__main__": # Initialize and run the server mcp.run(transport='stdio') ``` -------------------------------- ### Define Transport Interface in TypeScript Source: https://modelcontextprotocol.info/docs/concepts/transports The Transport interface defines the required methods for starting, sending, and closing connections, along with message and error 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; } ``` -------------------------------- ### Configure Filesystem Server Entry Source: https://modelcontextprotocol.info/docs/learning-path A snippet for adding the filesystem server to the configuration file. ```json "filesystem": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/safe/folder"] } ``` -------------------------------- ### Test MCP Server Logic and Compliance Source: https://modelcontextprotocol.info/docs/faqs Examples for unit testing server logic, verifying protocol compliance, and performing end-to-end AI integration tests. ```python def test_file_access_permissions(): server = FileSystemServer(allowed_paths=["/safe/"]) # Should succeed result = server.read_file("/safe/document.txt") assert result.success # Should fail with pytest.raises(PermissionError): server.read_file("/etc/passwd") ``` ```python def test_mcp_protocol_compliance(): client = MCPClient() client.connect(server_url) # Test capability discovery capabilities = client.list_capabilities() assert "read_files" in capabilities # Test actual operations result = client.call_tool("read_file", {"path": "/test.txt"}) assert result.status == "success" ``` ```python def test_claude_integration(): # Configure Claude with test server config = { "mcpServers": { "test": {"command": "python", "args": ["test_server.py"]} } } claude = ClaudeClient(config) response = claude.chat("Read the contents of test.txt") assert "file contents" in response.lower() ``` -------------------------------- ### Implement a basic MCP server Source: https://modelcontextprotocol.info/docs/concepts/architecture Basic server implementation demonstrating resource listing and transport connection. ```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); ``` ```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) ``` -------------------------------- ### Configure Client Capabilities Source: https://modelcontextprotocol.info/docs/sdk/java/mcp-client Enables specific features like filesystem roots and LLM sampling during client initialization. ```java var capabilities = ClientCapabilities.builder() .roots(true) // Enable filesystem roots support with list changes notifications .sampling() // Enable LLM sampling support .build(); ``` -------------------------------- ### Run MCP Client with Server Source: https://modelcontextprotocol.info/docs/tutorials/building-a-client Commands to execute the client with either a Python or Node.js server using uv. ```bash uv run client.py path/to/server.py # python server uv run client.py path/to/build/index.js # node server ``` -------------------------------- ### Interact with MCP Prompts in Java Source: https://modelcontextprotocol.info/docs/sdk/java/mcp-client Demonstrates listing and executing prompt templates using synchronous and asynchronous patterns. ```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(); ``` -------------------------------- ### Implement the main server function Source: https://modelcontextprotocol.info/docs/quickstart/quickstart Defines the entry point for the MCP server using stdio streams. ```python async def main(): # Run the server using stdin/stdout streams async with mcp.server.stdio.stdio_server() as (read_stream, write_stream): await server.run( read_stream, write_stream, InitializationOptions( server_name="weather", server_version="0.1.0", capabilities=server.get_capabilities( notification_options=NotificationOptions(), experimental_capabilities={}, ), ), ) # This is needed if you'd like to connect to a custom client if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Initialize MCP Server Instance Source: https://modelcontextprotocol.info/docs/quickstart/server Imports necessary SDK modules and initializes the 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", }); ``` -------------------------------- ### Configure Spring Boot MCP Client Starter Source: https://modelcontextprotocol.info/docs/quickstart/server Dependency and configuration properties for enabling auto-configured MCP clients in Spring Boot applications. ```xml org.springframework.ai spring-ai-mcp-client-spring-boot-starter ``` ```properties spring.ai.mcp.client.stdio.servers-configuration=file:PATH/TO/claude_desktop_config.json ``` -------------------------------- ### Create Main Application Class Source: https://modelcontextprotocol.info/docs/quickstart/client Standard Spring Boot entry point for the chatbot application. ```java package com.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class BraveChatApplication { public static void main(String[] args) { SpringApplication.run(BraveChatApplication.class, args); } } ``` -------------------------------- ### Configure pyproject.toml Source: https://modelcontextprotocol.info/docs/quickstart/quickstart Add the project script entry point to the pyproject.toml file. ```toml ...rest of config [build-system] requires = [ "hatchling",] build-backend = "hatchling.build" [project.scripts] weather = "weather:main" ``` -------------------------------- ### Access MCP Resources in Java Source: https://modelcontextprotocol.info/docs/sdk/java/mcp-client Demonstrates listing and retrieving resource content using synchronous and asynchronous patterns. ```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(); ``` -------------------------------- ### Implementing tool listing Source: https://modelcontextprotocol.info/docs/quickstart/quickstart Register available tools using the @server.list_tools() decorator and define their input schemas. ```python @server.list_tools() async def handle_list_tools() -> list[types.Tool]: """ List available tools. Each tool specifies its arguments using JSON Schema validation. """ return [ types.Tool( name="get-alerts", description="Get weather alerts for a state", inputSchema={ "type": "object", "properties": { "state": { "type": "string", "description": "Two-letter state code (e.g. CA, NY)", }, }, "required": ["state"], }, ), types.Tool( name="get-forecast", description="Get weather forecast for a location", inputSchema={ "type": "object", "properties": { "latitude": { "type": "number", "description": "Latitude of the location", }, "longitude": { "type": "number", "description": "Longitude of the location", }, }, "required": ["latitude", "longitude"], }, ), ] ``` -------------------------------- ### Implement ChatClient with MCP Tools Source: https://modelcontextprotocol.info/docs/quickstart/client Configures the ChatClient with system prompts, tool callbacks, and chat memory. ```java var chatClient = chatClientBuilder .defaultSystem("You are useful assistant, expert in AI and Java.") .defaultTools((Object[]) mcpToolAdapter.toolCallbacks()) .defaultAdvisors(new MessageChatMemoryAdvisor(new InMemoryChatMemory())) .build(); ``` -------------------------------- ### ServerCapabilities.builder() Source: https://modelcontextprotocol.info/docs/sdk/java/mcp-server Configures the capabilities of the MCP server, including support for resources, tools, prompts, and logging. ```APIDOC ## ServerCapabilities.builder() ### Description Configures the server's supported features. Use this to enable or disable resources, tools, prompts, and logging. ### Method Builder pattern ### Parameters - **resources(boolean, boolean)** - Configures resource support and list change notifications. - **tools(boolean)** - Configures tool support and list change notifications. - **prompts(boolean)** - Configures prompt support and list change notifications. - **logging()** - Enables logging support. ``` -------------------------------- ### Implement Sampling Support Source: https://modelcontextprotocol.info/docs/sdk/java/mcp-client Configures a sampling handler to allow servers to request LLM interactions through the client. ```java // Configure sampling handler Function samplingHandler = request -> { // Sampling implementation that interfaces with LLM return new CreateMessageResult(response); }; // Create client with sampling support var client = McpClient.sync(transport) .capabilities(ClientCapabilities.builder() .sampling() .build()) .sampling(samplingHandler) .build(); ``` -------------------------------- ### Initialize an asynchronous MCP client Source: https://modelcontextprotocol.info/docs/sdk/java/mcp-client Configures an asynchronous client using Project Reactor for non-blocking communication and sampling. ```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))) .build(); ``` -------------------------------- ### Connect to MCP Server Source: https://modelcontextprotocol.info/docs/quickstart/client Method to establish a connection to an MCP server and list 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]) ``` -------------------------------- ### Implement Transport with anyio in Python Source: https://modelcontextprotocol.info/docs/concepts/transports Use anyio for low-level transport implementation to ensure compatibility with asyncio-based MCP servers. ```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() ``` -------------------------------- ### Define YAML configuration and overrides Source: https://modelcontextprotocol.info/docs/best-practices Use base and environment-specific YAML files to manage server settings and overrides. ```yaml # config/base.yaml server: name: "my-mcp-server" version: "1.0.0" timeout: 30 max_connections: 100 logging: level: "INFO" format: "json" security: auth_required: true rate_limit: 1000 --- # config/production.yaml (overrides) logging: level: "WARN" security: rate_limit: 10000 monitoring: metrics_enabled: true health_check_interval: 30 ``` -------------------------------- ### Define Dynamic Prompt with Resource Context Source: https://modelcontextprotocol.info/docs/concepts/prompts Defines a prompt with required arguments and demonstrates how to include resource content in the response messages. ```json { "name": "analyze-project", "description": "Analyze project logs and code", "arguments": [ { "name": "timeframe", "description": "Time period to analyze logs", "required": true }, { "name": "fileUri", "description": "URI of code file to review", "required": true } ] } ``` ```json { "messages": [ { "role": "user", "content": { "type": "text", "text": "Analyze these system logs and the code file for any issues:" } }, { "role": "user", "content": { "type": "resource", "resource": { "uri": "logs://recent?timeframe=1h", "text": "[2024-03-14 15:32:11] ERROR: Connection timeout in network.py:127\n[2024-03-14 15:32:15] WARN: Retrying connection (attempt 2/3)\n[2024-03-14 15:32:20] ERROR: Max retries exceeded", "mimeType": "text/plain" } } }, { "role": "user", "content": { "type": "resource", "resource": { "uri": "file:///path/to/code.py", "text": "def connect_to_service(timeout=30):\n retries = 3\n for attempt in range(retries):\n try:\n return establish_connection(timeout)\n except TimeoutError:\n if attempt == retries - 1:\n raise\n time.sleep(5)\n\ndef establish_connection(timeout):\n # Connection implementation\n pass", "mimeType": "text/x-python" } } } ] } ``` -------------------------------- ### Configure MCP server for Claude Desktop Source: https://modelcontextprotocol.info/docs/quickstart/quickstart JSON configuration to register the weather server with Claude for Desktop. ```json { "mcpServers": { "weather": { "command": "uv", "args": [ "--directory", "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather", "run", "weather" ] } } } ``` ```json { "mcpServers": { "weather": { "command": "uv", "args": [ "--directory", "C:\\ABSOLUTE\PATH\TO\PARENT\FOLDER\weather", "run", "weather" ] } } } ``` -------------------------------- ### Open Claude Desktop configuration Source: https://modelcontextprotocol.info/docs/quickstart/quickstart Commands to open the configuration file for Claude for Desktop. ```bash code ~/Library/Application\ Support/Claude/claude_desktop_config.json ``` ```powershell code $env:AppData\Claude\claude_desktop_config.json ``` -------------------------------- ### Implement Server Connection Management Source: https://modelcontextprotocol.info/docs/tutorials/building-a-client Method to establish a connection to an MCP server via stdio and initialize the session. ```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]) ``` -------------------------------- ### Configure Spring Boot MCP Application Source: https://modelcontextprotocol.info/docs/quickstart/server Sets up the main application class and registers the WeatherService tools using MethodToolCallbackProvider. ```java @SpringBootApplication public class McpServerApplication { public static void main(String[] args) { SpringApplication.run(McpServerApplication.class, args); } @Bean public ToolCallbackProvider weatherTools(WeatherService weatherService) { return MethodToolCallbackProvider.builder().toolObjects(weatherService).build(); } } ``` -------------------------------- ### Define and serve prompts with MCP Python SDK Source: https://modelcontextprotocol.info/docs/concepts/prompts Uses the MCP Server class to register prompts and handle requests for prompt content. Requires the mcp package. ```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") ``` -------------------------------- ### Initialize MCP Client Manually in Java Source: https://modelcontextprotocol.info/docs/quickstart/server Uses McpClient to establish a synchronous connection to an MCP server via stdio and perform tool calls. ```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(); ```