### Project Setup and Dependency Installation (MacOS/Linux) Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/server.mdx Creates a new project directory, initializes an npm project, installs SDK and TypeScript dependencies, and creates necessary files and directories for a Node.js project. ```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 ``` -------------------------------- ### Project Setup and Dependency Installation (Windows) Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/server.mdx Creates a new project directory, initializes an npm project, installs SDK and TypeScript dependencies, and creates necessary files and directories for a Node.js project 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 Your Environment Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/client.mdx Instructions for setting up your local development environment to run the Brave Chatbot example, including installing npx, cloning the repository, setting API keys, and building the application. ```APIDOC ## Setting Up Your Environment 1. **Install npx:** ```bash npm install -g npx ``` (Ensure Node.js and npm are installed first). 2. **Clone the repository:** ```bash git clone https://github.com/spring-projects/spring-ai-examples.git cd model-context-protocol/brave-chatbot ``` 3. **Set API keys:** ```bash export ANTHROPIC_API_KEY='your-anthropic-api-key-here' export BRAVE_API_KEY='your-brave-api-key-here' ``` *Warning: Keep your API keys secure.* 4. **Build the application:** ```bash ./mvnw clean install ``` 5. **Run the application:** ```bash ./mvnw spring-boot:run ``` ``` -------------------------------- ### Setup MCP Client Environment (Windows) Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/client.mdx Steps to set up the development environment for the MCP client on Windows. This includes creating a project directory, initializing an npm project, installing dependencies, and creating the source file. ```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 ``` -------------------------------- ### Install and Run MCP Memory Server (Bash) Source: https://github.com/modelcontextprotocol/docs/blob/main/examples.mdx Installs and runs the in-memory MCP server directly using npx. This is a quick way to start an MCP server for testing or development. ```bash npx -y @modelcontextprotocol/server-memory ``` -------------------------------- ### Setup MCP Client Environment (MacOS/Linux) Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/client.mdx Steps to set up the development environment for the MCP client on macOS or Linux. This includes creating a project directory, initializing an npm project, installing dependencies, and creating the source file. ```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 ``` -------------------------------- ### Clone Spring AI Examples Repository Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/client.mdx Clones the Spring AI examples repository from GitHub 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 ``` -------------------------------- ### Initialize Node.js Project and Install Dependencies Source: https://github.com/modelcontextprotocol/docs/blob/main/tutorials/building-a-client-node.mdx Sets up a new Node.js project, initializes npm, installs necessary SDKs and development dependencies, and configures TypeScript for the project. ```bash mkdir mcp-client cd mcp-client npm init -y npm install @modelcontextprotocol/sdk @anthropic-ai/sdk dotenv npm install -D typescript @types/node npx tsc --init ``` -------------------------------- ### Install and Run MCP Git Server (Bash) Source: https://github.com/modelcontextprotocol/docs/blob/main/examples.mdx Demonstrates how to install and run the Git MCP server using both uvx and pip package managers. It also shows how to execute the server using Python. ```bash # Using uvx uvx mcp-server-git ``` ```bash # Using pip pip install mcp-server-git python -m mcp_server_git ``` -------------------------------- ### Install and Initialize MCP CLI Tool (Windows) Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/server.mdx Installs the 'uv' package manager and initializes a new Python project for an MCP weather server on Windows. It sets up the project directory, creates a virtual environment, and installs necessary dependencies like 'mcp[cli]' and 'httpx'. ```powershell powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" # 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 ``` -------------------------------- ### Kotlin SDK Setup Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/client.mdx Instructions for setting up the environment for the Kotlin MCP client, including system requirements and project initialization using Gradle. ```APIDOC ## System Requirements (Kotlin) - Java 17 or higher - Anthropic API key (Claude) ## Setting up your environment (Kotlin) 1. **Install Java and Gradle:** Download Java from the [official Oracle JDK website](https://www.oracle.com/java/technologies/downloads/). Verify Java installation: ```bash java --version ``` 2. **Create and set up your project:** **MacOS/Linux:** ```bash mkdir kotlin-mcp-client cd kotlin-mcp-client gradle init ``` **Windows:** ```powershell md kotlin-mcp-client cd kotlin-mcp-client ``` *Refer to the [Kotlin SDK samples](https://github.com/modelcontextprotocol/kotlin-sdk/tree/main/samples/kotlin-mcp-client) for complete code.* ``` -------------------------------- ### C# Project Setup and Dependencies Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/client.mdx Commands to create a new .NET console project and add necessary dependencies for the ModelContextProtocol C# SDK. ```bash dotnet new console -n QuickstartClient cd QuickstartClient ``` ```bash dotnet add package ModelContextProtocol --prerelease dotnet add package Anthropic.SDK dotnet add package Microsoft.Extensions.Hosting ``` -------------------------------- ### MCP Client - Correct Path Usage Examples Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/client.mdx Examples demonstrating correct path syntax for running the MCP client with different server locations and operating systems. Includes relative, absolute, and Windows-style paths. ```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 ``` -------------------------------- ### Setup Kotlin Project for Weather Server Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/server.mdx Provides commands to create a new directory, navigate into it, and initialize a new Kotlin project using Gradle for building a weather server. ```bash # Create a new directory for our project mkdir weather cd weather # Initialize a new kotlin project gradle init ``` -------------------------------- ### Create and Set Up C# Project (MacOS/Linux) Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/server.mdx Creates a new directory for a C# project, navigates into it, and initializes a new console application using the .NET CLI. Assumes .NET SDK is installed. ```bash # Create a new directory for our project mkdir weather cd weather # Initialize a new C# project dotnet new console ``` -------------------------------- ### Install Mintlify CLI Source: https://github.com/modelcontextprotocol/docs/blob/main/CONTRIBUTING.md Installs the Mintlify CLI globally using npm, a tool used for previewing documentation changes locally. ```shell npm i -g mintlify ``` -------------------------------- ### Main Execution Entry Point (TypeScript) Source: https://github.com/modelcontextprotocol/docs/blob/main/tutorials/building-a-client-node.mdx Sets up and runs the MCP client application. It parses command-line arguments to get the server script path, connects to the server, and starts the chat loop. Includes error handling and ensures cleanup occurs on exit. This script is intended to be run with `ts-node`. ```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; ``` -------------------------------- ### Setup Kotlin Project for Weather Server (Windows) Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/server.mdx Provides commands to create a new directory, navigate into it, and initialize a new Kotlin project using Gradle for building a weather server on Windows. ```powershell # Create a new directory for our project md weather cd weather # Initialize a new kotlin project gradle init ``` -------------------------------- ### Install and Initialize MCP CLI Tool (MacOS/Linux) Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/server.mdx Installs the 'uv' package manager and initializes a new Python project for an MCP weather server on MacOS or Linux. It sets up the project directory, creates a virtual environment, and installs necessary dependencies like 'mcp[cli]' and 'httpx'. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh # 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 ``` -------------------------------- ### Image Analysis Command Example Source: https://github.com/modelcontextprotocol/docs/blob/main/CLAUDE.md An example of how to format a command for image analysis, including the command and the image path. ```bash $ claude "Analyze this image: /path/to/image.png" ``` -------------------------------- ### SSE Transport Setup (Python) Source: https://github.com/modelcontextprotocol/docs/blob/main/docs/concepts/transports.mdx Provides examples for setting up the Server-Sent Events (SSE) transport in Python for MCP. This facilitates server-to-client streaming communication via HTTP. ```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() ``` -------------------------------- ### Verify .NET Installation Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/server.mdx Checks the installed version of the .NET SDK. This command requires the .NET SDK to be installed on the system. ```bash dotnet --version ``` -------------------------------- ### Example Tool Definitions Source: https://github.com/modelcontextprotocol/docs/blob/main/docs/concepts/tools.mdx Examples of defining different types of tools with their respective input schemas. ```APIDOC ## Tool Definition Structure Each tool is defined with the following structure: ```typescript { name: string; // Unique identifier for the tool description?: string; // Human-readable description inputSchema: { type: "object", // JSON Schema for the tool's parameters properties: { ... } // Tool-specific parameters } } ``` ### System Operations Example ```json { "name": "execute_command", "description": "Run a shell command", "inputSchema": { "type": "object", "properties": { "command": { "type": "string" }, "args": { "type": "array", "items": { "type": "string" } } } } } ``` ### API Integrations Example ```json { "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" } } } } } ``` ### Data Processing Example ```json { "name": "analyze_csv", "description": "Analyze a CSV file", "inputSchema": { "type": "object", "properties": { "filepath": { "type": "string" }, "operations": { "type": "array", "items": { "enum": ["sum", "average", "count"] } } } } } ``` ``` -------------------------------- ### Verify Java Installation Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/client.mdx Checks the installed Java version on the system. This command verifies that Java is correctly installed and accessible from the command line. ```bash java --version ``` -------------------------------- ### Run Mintlify Development Server Source: https://github.com/modelcontextprotocol/docs/blob/main/CONTRIBUTING.md Starts the Mintlify development server to preview documentation changes locally. This command is essential for testing modifications before submitting them. ```shell mintlify dev ``` -------------------------------- ### Configure MCP Servers in JSON Source: https://github.com/modelcontextprotocol/docs/blob/main/examples.mdx Provides a JSON configuration example for setting up various MCP servers, including memory, filesystem, and GitHub. It shows how to specify commands, arguments, and environment variables for each server. ```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": "" } } } } ``` -------------------------------- ### MCP Client Implementation Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/client.mdx Code examples for implementing the MCP client, including connecting to an MCP server and managing server connections. ```APIDOC ## Creating the Client ### Basic Client Structure Initialize the MCP client and the Anthropic client: ```kotlin import io.modelcontextprotocol. MCPClient import com.anthropic.types.ToolUnion import com.anthropic.resources.Tool import io.modelcontextprotocol.client.Client import io.modelcontextprotocol.client.Implementation import io.modelcontextprotocol.client.StdioClientTransport import io.modelcontextprotocol.client.Client import io.modelcontextprotocol.client.Implementation import io.modelcontextprotocol.client.StdioClientTransport import io.modelcontextprotocol.client.Client import io.modelcontextprotocol.client.Implementation import io.modelcontextprotocol.client.StdioClientTransport import com.anthropic.types.ToolUnion import com.anthropic.resources.Tool import com.anthropic.resources.Tool import io.modelcontextprotocol.client.Client import io.modelcontextprotocol.client.Implementation import io.modelcontextprotocol.client.StdioClientTransport import com.anthropic.types.ToolUnion import com.anthropic.resources.Tool import io.modelcontextprotocol.client.Client import io.modelcontextprotocol.client.Implementation import io.modelcontextprotocol.client.StdioClientTransport import com.anthropic.types.ToolUnion import com.anthropic.resources.Tool import com.anthropic.resources.Tool import io.modelcontextprotocol.client.Client import io.modelcontextprotocol.client.Implementation import io.modelcontextprotocol.client.StdioClientTransport import com.anthropic.types.ToolUnion import com.anthropic.resources.Tool import com.anthropic.resources.Tool import kotlinx.coroutines.runBlocking import okio.BufferedSource import okio.BufferedSink import okio.asSource import okio.asSink import com.anthropic.models.AnthropicOkHttpClient import org.slf4j.Logger import org.slf4j.LoggerFactory import com.anthropic.models.AnthropicOkHttpClient import org.slf4j.Logger import org.slf4j.LoggerFactory import com.anthropic.models.AnthropicOkHttpClient import org.slf4j.Logger import org.slf4j.LoggerFactory import com.anthropic.models.AnthropicOkHttpClient import org.slf4j.Logger import org.slf4j.LoggerFactory import com.google.gson.JsonObject import com.google.gson.JsonParser import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.node.ObjectNode import com.anthropic.util.JsonValue class MCPClient : AutoCloseable { private val anthropic = AnthropicOkHttpClient.fromEnv() private val mcp: Client = Client(clientInfo = Implementation(name = "mcp-client-cli", version = "1.0.0")) private lateinit var tools: List // methods will go here override fun close() { runBlocking { mcp.close() anthropic.close() } } ``` ### Server connection management Implement the method to connect to an MCP server: ```kotlin suspend fun connectToServer(serverScriptPath: String) { try { val command = buildList { when (serverScriptPath.substringAfterLast(".")) { "js" -> add("node") "py" -> add(if (System.getProperty("os.name").lowercase().contains("win")) "python" else "python3") "jar" -> addAll(listOf("java", "-jar")) else -> throw IllegalArgumentException("Server script must be a .js, .py or .jar file") } add(serverScriptPath) } val process = ProcessBuilder(command).start() val transport = StdioClientTransport( input = process.inputStream.asSource().buffered(), output = process.outputStream.asSink().buffered() ) mcp.connect(transport) val toolsResult = mcp.listTools() tools = toolsResult?.tools?.map { ToolUnion.ofTool( Tool.builder() .name(it.name) .description(it.description ?: "") .inputSchema( Tool.InputSchema.builder() .type(JsonValue.from(it.inputSchema.type)) .properties(it.inputSchema.properties.toJsonValue()) .putAdditionalProperty("required", JsonValue.from(it.inputSchema.required)) .build() ) .build() ) } ?: emptyList() println("Connected to server with tools: ${tools.joinToString(", ") { it.tool().get().name() }}") } catch (e: Exception) { println("Failed to connect to MCP server: $e") throw e } } private fun JsonObject.toJsonValue(): JsonValue { val mapper = ObjectMapper() val node = mapper.readTree(this.toString()) return JsonValue.fromJsonNode(node) } ``` ``` -------------------------------- ### Verify Node.js and npm Installation Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/server.mdx Checks if Node.js and npm are installed and their versions. Requires Node.js to be installed. ```bash node --version npm --version ``` -------------------------------- ### Build and Run Application with Maven Wrapper (Alternative) Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/client.mdx Builds and runs the Spring Boot application using the Maven wrapper. This is an alternative method to start the application after building. ```bash ./mvnw clean install java -jar ./target/ai-mcp-brave-chatbot-0.0.1-SNAPSHOT.jar ``` -------------------------------- ### Install npx using npm Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/client.mdx Installs the Node Package eXecute (npx) globally using npm, a prerequisite for running some MCP server commands. ```bash npm install -g npx ``` -------------------------------- ### Import MCP Server and Setup Instance Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/server.mdx Imports necessary classes from the Model Context Protocol SDK and initializes an McpServer instance with basic configuration including name, version, and capabilities. ```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", capabilities: { resources: {}, tools: {}, }, }); ``` -------------------------------- ### Example client path usage Source: https://github.com/modelcontextprotocol/docs/blob/main/tutorials/building-a-client-node.mdx Demonstrates correct usage of paths for server scripts when running the client, including relative paths, absolute paths, and Windows-specific path formats. This ensures the client can locate and connect to the server correctly. ```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 ``` -------------------------------- ### Example Path Usage (Bash) Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/client.mdx Demonstrates correct path formats for running the MCP client on different operating systems. Covers relative paths, absolute paths, and Windows-specific path formats, including forward and backward slashes. ```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 Server Implementation Example (TypeScript) Source: https://github.com/modelcontextprotocol/docs/blob/main/docs/concepts/architecture.mdx A basic example demonstrating how to implement an MCP server in TypeScript. It sets up a server instance, defines a request handler for listing resources, and connects to a stdio transport. ```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); ``` -------------------------------- ### Stdio Transport Setup (Python) Source: https://github.com/modelcontextprotocol/docs/blob/main/docs/concepts/transports.mdx Illustrates the setup for the standard input/output transport in Python for both server and client applications. This transport is ideal for process-to-process communication. ```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() ``` -------------------------------- ### Run Application using Maven Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/client.mdx Runs the Spring Boot application using the Maven wrapper. This command starts the application in the current directory. ```bash ./mvnw spring-boot:run ``` -------------------------------- ### Configure Environment Variables for Server Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/user.mdx JSON configuration example for setting environment variables, specifically APPDATA and an API key, for a Brave Search server in Claude Desktop. ```json { "brave-search": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-brave-search"], "env": { "APPDATA": "C:\\Users\\user\\AppData\\Roaming\\", "BRAVE_API_KEY": "..." } } } ``` -------------------------------- ### Java Server Path Execution Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/client.mdx Examples of how to execute a Java client JAR with a server JAR path, demonstrating relative, absolute, and Windows path formats. ```bash java -jar build/libs/client.jar ./server/build/libs/server.jar ``` ```bash java -jar build/libs/client.jar /Users/username/projects/mcp-server/build/libs/server.jar ``` ```bash java -jar build/libs/client.jar C:/projects/mcp-server/build/libs/server.jar ``` ```bash java -jar build/libs/client.jar C:\\projects\\mcp-server\\build\\libs\\server.jar ``` -------------------------------- ### MCP Server Implementation Example (Python) Source: https://github.com/modelcontextprotocol/docs/blob/main/docs/concepts/architecture.mdx A basic example demonstrating how to implement an MCP server in Python. It defines a server instance and a handler for the list_resources RPC method, then runs the server using stdio 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()) ``` -------------------------------- ### Example MCP Server Description for LLM Source: https://github.com/modelcontextprotocol/docs/blob/main/tutorials/building-mcp-with-llms.mdx This snippet shows a clear, structured prompt to an LLM for building an MCP server. It outlines the desired resources, tools, prompts, and external system integrations. ```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 ``` -------------------------------- ### Multi-step Workflow Example (TypeScript) Source: https://github.com/modelcontextprotocol/docs/blob/main/docs/concepts/prompts.mdx Provides a TypeScript example of a multi-step workflow for debugging, demonstrating how to define a prompt that generates a sequence of user and assistant messages based on an error input. ```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." } } ]; } }; ``` -------------------------------- ### Initialize Python Environment with uv Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/client.mdx Sets up a new Python project using 'uv', creates and activates a virtual environment, and installs necessary packages like 'mcp', 'anthropic', and 'python-dotenv'. It also removes default files and creates a new 'client.py' file. ```bash 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 main.py # Create our main file touch client.py ``` -------------------------------- ### Configure Filesystem MCP Server (macOS/Linux) Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/user.mdx This JSON configuration adds the 'filesystem' MCP server to Claude for Desktop. It specifies using 'npx' to run the '@modelcontextprotocol/server-filesystem' package with arguments for user-accessible directories. Ensure Node.js is installed. ```json { "mcpServers": { "filesystem": { "command": "npx", "args": [ "-y", "@modelcontextprotocol/server-filesystem", "/Users/username/Desktop", "/Users/username/Downloads" ] } } } ``` -------------------------------- ### Install NPM Globally Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/user.mdx Command to install Node Package Manager (NPM) globally, which may be required for the `npx` command to function correctly. ```bash npm install -g npm ``` -------------------------------- ### Verify Node.js Installation Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/user.mdx This command checks if Node.js is installed and accessible on your system. It's a prerequisite for running MCP servers that rely on Node. If an error occurs, download Node.js from nodejs.org. ```bash node --version ``` -------------------------------- ### Stdio Transport Setup (TypeScript) Source: https://github.com/modelcontextprotocol/docs/blob/main/docs/concepts/transports.mdx Demonstrates how to establish communication using the standard input/output transport for both server and client sides in TypeScript. This is useful for command-line tools and local integrations. ```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); ``` -------------------------------- ### Define Main Entry Point for Kotlin MCP Client Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/client.mdx Sets up the main execution function for the MCP client. It validates command-line arguments to ensure the server path is provided, initializes the MCPClient, connects to the server, and starts the chat loop. It uses 'runBlocking' for coroutine execution. ```kotlin fun main(args: Array) = runBlocking { if (args.isEmpty()) throw IllegalArgumentException("Usage: java -jar /build/libs/kotlin-mcp-client-0.1.0-all.jar ") val serverPath = args.first() val client = MCPClient() client.use { client.connectToServer(serverPath) client.chatLoop() } } ``` -------------------------------- ### Implement Weather Alerts and Forecast Tools with Kotlin HTTP Client Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/server.mdx This snippet demonstrates how to set up an HTTP client using Kotlin's HttpClient and register two tools: one to get weather alerts by state and another to get weather forecasts by latitude and longitude. It includes defining input schemas and handling request arguments. ```kotlin val httpClient = HttpClient { defaultRequest { url("https://api.weather.gov") headers { append("Accept", "application/geo+json") append("User-Agent", "WeatherApiClient/1.0") } contentType(ContentType.Application.Json) } // Install content negotiation plugin for JSON serialization/deserialization install(ContentNegotiation) { json(Json { ignoreUnknownKeys = true }) } } // Register a tool to fetch weather alerts by state server.addTool( name = "get_alerts", description = """ Get weather alerts for a US state. Input is Two-letter US state code (e.g. CA, NY) """, inputSchema = Tool.Input( properties = buildJsonObject { putJsonObject("state") { put("type", "string") put("description", "Two-letter US state code (e.g. CA, NY)") } }, required = listOf("state") ) ) { request -> val state = request.arguments["state"]?.jsonPrimitive?.content if (state == null) { return@addTool CallToolResult( content = listOf(TextContent("The 'state' parameter is required.")) ) } val alerts = httpClient.getAlerts(state) CallToolResult(content = alerts.map { TextContent(it) }) } // Register a tool to fetch weather forecast by latitude and longitude server.addTool( name = "get_forecast", description = """ Get weather forecast for a specific latitude/longitude """, inputSchema = Tool.Input( properties = buildJsonObject { putJsonObject("latitude") { put("type", "number") } putJsonObject("longitude") { put("type", "number") } }, required = listOf("latitude", "longitude") ) ) { request -> val latitude = request.arguments["latitude"]?.jsonPrimitive?.doubleOrNull val longitude = request.arguments["longitude"]?.jsonPrimitive?.doubleOrNull if (latitude == null || longitude == null) { return@addTool CallToolResult( content = listOf(TextContent("The 'latitude' and 'longitude' parameters are required.")) ) } val forecast = httpClient.getForecast(latitude, longitude) CallToolResult(content = forecast.map { TextContent(it) }) } ``` -------------------------------- ### Example Transport with Error Handling (Python) Source: https://github.com/modelcontextprotocol/docs/blob/main/docs/concepts/transports.mdx Illustrates a Python example of a transport implementation using `anyio`. It includes detailed error handling for message processing and transport initialization, logging errors and ensuring proper resource cleanup. ```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 ``` -------------------------------- ### Configure package.json for Node.js Project Source: https://github.com/modelcontextprotocol/docs/blob/main/tutorials/building-a-client-node.mdx Configures the 'package.json' file for a Node.js project by setting the module type to 'module' and defining build and start scripts. ```json { "type": "module", "scripts": { "build": "tsc", "start": "node build/client.js" } } ``` -------------------------------- ### Implement Basic Tool (Python) Source: https://github.com/modelcontextprotocol/docs/blob/main/docs/concepts/tools.mdx Example of implementing a basic tool ('calculate_sum') in an MCP server using Python. It shows how to register tool definitions and handle tool calls. ```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}") ``` -------------------------------- ### Run the MCP Server (Bash) Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/server.mdx Command to compile and run the MCP server application using the .NET CLI. This command starts the server, which will then listen for incoming requests on standard input and output. ```bash dotnet run ``` -------------------------------- ### Example Transport Implementation with Error Handling (TypeScript) Source: https://github.com/modelcontextprotocol/docs/blob/main/docs/concepts/transports.mdx Demonstrates an example implementation of the `Transport` interface in TypeScript, including error handling for connection and message sending operations. Errors are caught and reported via the `onerror` callback. ```typescript class ExampleTransport implements Transport { async start() { try { // Connection logic } catch (error) { this.onerror?.(new Error(`Failed to connect: ${error}`)); throw error; } } async send(message: JSONRPCMessage) { try { // Sending logic } catch (error) { this.onerror?.(new Error(`Failed to send message: ${error}`)); throw error; } } } ``` -------------------------------- ### Example Tool: Execute Shell Command Source: https://github.com/modelcontextprotocol/docs/blob/main/docs/concepts/tools.mdx Schema definition for a tool that executes a shell command on the server. It accepts the command name and an array of string arguments. ```typescript { name: "execute_command", description: "Run a shell command", inputSchema: { type: "object", properties: { command: { type: "string" }, args: { type: "array", items: { type: "string" } } } } } ``` -------------------------------- ### Implement Basic Tool (TypeScript) Source: https://github.com/modelcontextprotocol/docs/blob/main/docs/concepts/tools.mdx Example of implementing a basic tool ('calculate_sum') in an MCP server using TypeScript. It demonstrates how to define available tools and handle tool execution requests. ```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"); }); ``` -------------------------------- ### Multi-step Workflows Source: https://github.com/modelcontextprotocol/docs/blob/main/docs/concepts/prompts.mdx Illustrates the definition of a multi-step workflow prompt that guides a conversational interaction. ```APIDOC ## Multi-step Workflows ### Description Shows how to define a prompt that orchestrates a sequence of user and assistant messages to guide a specific workflow, such as debugging. ### Workflow Definition Example ```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." } } ]; } }; ``` ``` -------------------------------- ### Initialize FastMCP Server and Define Constants (Python) Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/server.mdx Initializes the FastMCP server for a weather application and defines constants for the National Weather Service API base URL and a user agent. This code forms the initial setup for an MCP server in Python. ```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" ``` -------------------------------- ### MCP Client Sync API Java Example Source: https://github.com/modelcontextprotocol/docs/blob/main/sdk/java/mcp-client.mdx Demonstrates how to use the synchronous MCP client API in Java. It covers client creation with custom configurations, initializing the connection, listing tools, calling tools, managing resources, interacting with prompts, adding/removing roots, and closing the client. ```java import java.time.Duration; import java.util.Map; // 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(); ``` -------------------------------- ### Spring Boot Application Setup (Java) Source: https://github.com/modelcontextprotocol/docs/blob/main/quickstart/server.mdx Configures the main Spring Boot application to register the WeatherService as an MCP tool. It utilizes MethodToolCallbackProvider to expose the service's methods for use by the MCP server. Requires Spring Boot and Spring AI dependencies. ```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(); } } ``` -------------------------------- ### Example Tool: GitHub Create Issue Source: https://github.com/modelcontextprotocol/docs/blob/main/docs/concepts/tools.mdx Schema definition for a tool that creates a GitHub issue. It includes properties for the issue title, body, and an array of 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" } } } } } ``` -------------------------------- ### SSE Transport Setup (TypeScript) Source: https://github.com/modelcontextprotocol/docs/blob/main/docs/concepts/transports.mdx Shows how to configure the Server-Sent Events (SSE) transport for MCP servers and clients using TypeScript. This enables server-to-client streaming 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); ``` -------------------------------- ### Example Sampling Request (JSON) Source: https://github.com/modelcontextprotocol/docs/blob/main/docs/concepts/sampling.mdx Demonstrates a complete JSON request object for initiating a sampling operation. It includes the method, parameters such as messages, system prompt, context inclusion, and token limits, sent from a server to a client. ```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 } } ```