Spaces:
Running
Running
File size: 70,563 Bytes
f468451 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
{
"docs": [
{
"id": "doc_modelcontextprotocol.io_docs_getting-started_intro_ab570992",
"url": "https://modelcontextprotocol.io/docs/getting-started/intro",
"title": "What is the Model Context Protocol (MCP)? - Model Context Protocol",
"content": "What can MCP enable?\n- Agents can access your Google Calendar and Notion, acting as a more personalized AI assistant.\n- Claude Code can generate an entire web app using a Figma design.\n- Enterprise chatbots can connect to multiple databases across an organization, empowering users to analyze data using chat.\n- AI models can create 3D designs on Blender and print them out using a 3D printer.\nWhy does MCP matter?\nDepending on where you sit in the ecosystem, MCP can have a range of benefits.- Developers: MCP reduces development time and complexity when building, or integrating with, an AI application or agent.\n- AI applications or agents: MCP provides access to an ecosystem of data sources, tools and apps which will enhance capabilities and improve the end-user experience.\n- End-users: MCP results in more capable AI applications or agents which can access your data and take actions on your behalf when necessary.\nStart Building\nBuild servers\nCreate MCP servers to expose your data and tools\nBuild clients\nDevelop applications that connect to MCP servers",
"updated_at": ""
},
{
"id": "doc_modelcontextprotocol.io_docs_learn_architecture_669def4e",
"url": "https://modelcontextprotocol.io/docs/learn/architecture",
"title": "Architecture overview - Model Context Protocol",
"content": "Scope\nThe Model Context Protocol includes the following projects:- MCP Specification: A specification of MCP that outlines the implementation requirements for clients and servers.\n- MCP SDKs: SDKs for different programming languages that implement MCP.\n- MCP Development Tools: Tools for developing MCP servers and clients, including the MCP Inspector\n- MCP Reference Server Implementations: Reference implementations of MCP servers.\nMCP focuses solely on the protocol for context exchange—it does not dictate\nhow AI applications use LLMs or manage the provided context.\nConcepts of MCP\nParticipants\nMCP follows a client-server architecture where an MCP host — an AI application like Claude Code or Claude Desktop — establishes connections to one or more MCP servers. The MCP host accomplishes this by creating one MCP client for each MCP server. Each MCP client maintains a dedicated one-to-one connection with its corresponding MCP server. The key participants in the MCP architecture are:- MCP Host: The AI application that coordinates and manages one or multiple MCP clients\n- MCP Client: A component that maintains a connection to an MCP server and obtains context from an MCP server for the MCP host to use\n- MCP Server: A program that provides context to MCP clients\nLayers\nMCP consists of two layers:- Data layer: Defines the JSON-RPC based protocol for client-server communication, including lifecycle management, and core primitives, such as tools, resources, prompts and notifications.\n- Transport layer: Defines the communication mechanisms and channels that enable data exchange between clients and servers, including transport-specific connection establishment, message framing, and authorization.\nData layer\nThe data layer implements a JSON-RPC 2.0 based exchange protocol that defines the message structure and semantics. This layer includes:- Lifecycle management: Handles connection initialization, capability negotiation, and connection termination between clients and servers\n- Server features: Enables servers to provide core functionality including tools for AI actions, resources for context data, and prompts for interaction templates from and to the client\n- Client features: Enables servers to ask the client to sample from the host LLM, elicit input from the user, and log messages to the client\n- Utility features: Supports additional capabilities like notifications for real-time updates and progress tracking for long-running operations\nTransport layer\nThe transport layer manages communication channels and authentication between clients and servers. It handles connection establishment, message framing, and secure communication between MCP participants. MCP supports two transport mechanisms:- Stdio transport: Uses standard input/output streams for direct process communication between local processes on the same machine, providing optimal performance with no network overhead.\n- Streamable HTTP transport: Uses HTTP POST for client-to-server messages with optional Server-Sent Events for streaming capabilities. This transport enables remote server communication and supports standard HTTP authentication methods including bearer tokens, API keys, and custom headers. MCP recommends using OAuth to obtain authentication tokens.\nData Layer Protocol\nA core part of MCP is defining the schema and semantics between MCP clients and MCP servers. Developers will likely find the data layer — in particular, the set of primitives — to be the most interesting part of MCP. It is the part of MCP that defines the ways developers can share context from MCP servers to MCP clients. MCP uses JSON-RPC 2.0 as its underlying RPC protocol. Client and servers send requests to each other and respond accordingly. Notifications can be used when no response is required.Lifecycle management\nMCP is a that requires lifecycle management. The purpose of lifecycle management is to negotiate the that both client and server support. Detailed information can be found in the specification, and the example showcases the initialization sequence.Primitives\nMCP primitives are the most important concept within MCP. They define what clients and servers can offer each other. These primitives specify the types of contextual information that can be shared with AI applications and the range of actions that can be performed. MCP defines three core primitives that servers can expose:- Tools: Executable functions that AI applications can invoke to perform actions (e.g., file operations, API calls, database queries)\n- Resources: Data sources that provide contextual information to AI applications (e.g., file contents, database records, API responses)\n- Prompts: Reusable templates that help structure interactions with language models (e.g., system prompts, few-shot examples)\n*/list\n), retrieval (*/get\n), and in some cases, execution (tools/call\n).\nMCP clients will use the */list\nmethods to discover available primitives. For example, a client can first list all available tools (tools/list\n) and then execute them. This design allows listings to be dynamic.\nAs a concrete example, consider an MCP server that provides context about a database. It can expose tools for querying the database, a resource that contains the schema of the database, and a prompt that includes few-shot examples for interacting with the tools.\nFor more details about server primitives see server concepts.\nMCP also defines primitives that clients can expose. These primitives allow MCP server authors to build richer interactions.\n- Sampling: Allows servers to request language model completions from the client’s AI application. This is useful when servers’ authors want access to a language model, but want to stay model independent and not include a language model SDK in their MCP server. They can use the\nsampling/complete\nmethod to request a language model completion from the client’s AI application. - Elicitation: Allows servers to request additional information from users. This is useful when servers’ authors want to get more information from the user, or ask for confirmation of an action. They can use the\nelicitation/request\nmethod to request additional information from the user. - Logging: Enables servers to send log messages to clients for debugging and monitoring purposes.\nNotifications\nThe protocol supports real-time notifications to enable dynamic updates between servers and clients. For example, when a server’s available tools change—such as when new functionality becomes available or existing tools are modified—the server can send tool update notifications to inform connected clients about these changes. Notifications are sent as JSON-RPC 2.0 notification messages (without expecting a response) and enable MCP servers to provide real-time updates to connected clients.Example\nData Layer\nThis section provides a step-by-step walkthrough of an MCP client-server interaction, focusing on the data layer protocol. We’ll demonstrate the lifecycle sequence, tool operations, and notifications using JSON-RPC 2.0 messages.1\nInitialization (Lifecycle Management)\nMCP begins with lifecycle management through a capability negotiation handshake. As described in the lifecycle management section, the client sends an\ninitialize\nrequest to establish the connection and negotiate supported features.Understanding the Initialization Exchange\nThe initialization process is a key part of MCP’s lifecycle management and serves several critical purposes:-\nProtocol Version Negotiation: The\nprotocolVersion\nfield (e.g., “2025-06-18”) ensures both client and server are using compatible protocol versions. This prevents communication errors that could occur when different versions attempt to interact. If a mutually compatible version is not negotiated, the connection should be terminated. -\nCapability Discovery: The\ncapabilities\nobject allows each party to declare what features they support, including which primitives they can handle (tools, resources, prompts) and whether they support features like notifications. This enables efficient communication by avoiding unsupported operations. -\nIdentity Exchange: The\nclientInfo\nandserverInfo\nobjects provide identification and versioning information for debugging and compatibility purposes.\n\"elicitation\": {}\n- The client declares it can work with user interaction requests (can receiveelicitation/create\nmethod calls)\n\"tools\": {\"listChanged\": true}\n- The server supports the tools primitive AND can sendtools/list_changed\nnotifications when its tool list changes\"resources\": {}\n- The server also supports the resources primitive (can handleresources/list\nandresources/read\nmethods)\nNotification\nHow This Works in AI Applications\nDuring initialization, the AI application’s MCP client manager establishes connections to configured servers and stores their capabilities for later use. The application uses this information to determine which servers can provide specific types of functionality (tools, resources, prompts) and whether they support real-time updates.Pseudo-code for AI application initialization\n2\nTool Discovery (Primitives)\nNow that the connection is established, the client can discover available tools by sending a\ntools/list\nrequest. This request is fundamental to MCP’s tool discovery mechanism — it allows clients to understand what tools are available on the server before attempting to use them.Understanding the Tool Discovery Request\nThetools/list\nrequest is simple, containing no parameters.Understanding the Tool Discovery Response\nThe response contains atools\narray that provides comprehensive metadata about each available tool. This array-based structure allows servers to expose multiple tools simultaneously while maintaining clear boundaries between different functionalities.Each tool object in the response includes several key fields:name\n: A unique identifier for the tool within the server’s namespace. This serves as the primary key for tool execution and should follow a clear naming pattern (e.g.,calculator_arithmetic\nrather than justcalculate\n)title\n: A human-readable display name for the tool that clients can show to usersdescription\n: Detailed explanation of what the tool does and when to use itinputSchema\n: A JSON Schema that defines the expected input parameters, enabling type validation and providing clear documentation about required and optional parameters\nHow This Works in AI Applications\nThe AI application fetches available tools from all connected MCP servers and combines them into a unified tool registry that the language model can access. This allows the LLM to understand what actions it can perform and automatically generates the appropriate tool calls during conversations.Pseudo-code for AI application tool discovery\n3\nTool Execution (Primitives)\nThe client can now execute a tool using the\ntools/call\nmethod. This demonstrates how MCP primitives are used in practice: after discovering available tools, the client can invoke them with appropriate arguments.Understanding the Tool Execution Request\nThetools/call\nrequest follows a structured format that ensures type safety and clear communication between client and server. Note that we’re using the proper tool name from the discovery response (weather_current\n) rather than a simplified name:Key Elements of Tool Execution\nThe request structure includes several important components:-\nname\n: Must match exactly the tool name from the discovery response (weather_current\n). This ensures the server can correctly identify which tool to execute. -\narguments\n: Contains the input parameters as defined by the tool’sinputSchema\n. In this example:location\n: “San Francisco” (required parameter)units\n: “imperial” (optional parameter, defaults to “metric” if not specified)\n-\nJSON-RPC Structure: Uses standard JSON-RPC 2.0 format with unique\nid\nfor request-response correlation.\nUnderstanding the Tool Execution Response\nThe response demonstrates MCP’s flexible content system:-\ncontent\nArray: Tool responses return an array of content objects, allowing for rich, multi-format responses (text, images, resources, etc.) -\nContent Types: Each content object has a\ntype\nfield. In this example,\"type\": \"text\"\nindicates plain text content, but MCP supports various content types for different use cases. - Structured Output: The response provides actionable information that the AI application can use as context for language model interactions.\nHow This Works in AI Applications\nWhen the language model decides to use a tool during a conversation, the AI application intercepts the tool call, routes it to the appropriate MCP server, executes it, and returns the results back to the LLM as part of the conversation flow. This enables the LLM to access real-time data and perform actions in the external world.4\nReal-time Updates (Notifications)\nMCP supports real-time notifications that enable servers to inform clients about changes without being explicitly requested. This demonstrates the notification system, a key feature that keeps MCP connections synchronized and responsive.\nUnderstanding Tool List Change Notifications\nWhen the server’s available tools change—such as when new functionality becomes available, existing tools are modified, or tools become temporarily unavailable—the server can proactively notify connected clients:Request\nKey Features of MCP Notifications\n-\nNo Response Required: Notice there’s no\nid\nfield in the notification. This follows JSON-RPC 2.0 notification semantics where no response is expected or sent. -\nCapability-Based: This notification is only sent by servers that declared\n\"listChanged\": true\nin their tools capability during initialization (as shown in Step 1). - Event-Driven: The server decides when to send notifications based on internal state changes, making MCP connections dynamic and responsive.\nClient Response to Notifications\nUpon receiving this notification, the client typically reacts by requesting the updated tool list. This creates a refresh cycle that keeps the client’s understanding of available tools current:Request\nWhy Notifications Matter\nThis notification system is crucial for several reasons:- Dynamic Environments: Tools may come and go based on server state, external dependencies, or user permissions\n- Efficiency: Clients don’t need to poll for changes; they’re notified when updates occur\n- Consistency: Ensures clients always have accurate information about available server capabilities\n- Real-time Collaboration: Enables responsive AI applications that can adapt to changing contexts",
"updated_at": ""
},
{
"id": "doc_modelcontextprotocol.io_docs_learn_server-concepts_01f4e91c",
"url": "https://modelcontextprotocol.io/docs/learn/server-concepts",
"title": "Understanding MCP servers - Model Context Protocol",
"content": "Core Server Features\nServers provide functionality through three building blocks: We will use a hypothetical scenario to demonstrate the role of each of these features, and show how they can work together.Tools\nTools enable AI models to perform actions. Each tool defines a specific operation with typed inputs and outputs. The model requests tool execution based on context.How Tools Work\nTools are schema-defined interfaces that LLMs can invoke. MCP uses JSON Schema for validation. Each tool performs a single operation with clearly defined inputs and outputs. Tools may require user consent prior to execution, helping to ensure users maintain control over actions taken by a model. Protocol operations: Example tool definition:Example: Travel Booking\nTools enable AI applications to perform actions on behalf of users. In a travel planning scenario, the AI application might use several tools to help book a vacation: Flight SearchUser Interaction Model\nTools are model-controlled, meaning AI models can discover and invoke them automatically. However, MCP emphasizes human oversight through several mechanisms. For trust and safety, applications can implement user control through various mechanisms, such as:- Displaying available tools in the UI, enabling users to define whether a tool should be made available in specific interactions\n- Approval dialogs for individual tool executions\n- Permission settings for pre-approving certain safe operations\n- Activity logs that show all tool executions with their results\nResources\nResources provide structured access to information that the AI application can retrieve and provide to models as context.How Resources Work\nResources expose data from files, APIs, databases, or any other source that an AI needs to understand context. Applications can access this information directly and decide how to use it - whether that’s selecting relevant portions, searching with embeddings, or passing it all to the model. Each resource has a unique URI (likefile:///path/to/document.md\n) and declares its MIME type for appropriate content handling. They declare MIME types for appropriate content handling and support two discovery patterns:\n- Direct Resources - fixed URIs that point to specific data. Example:\ncalendar://events/2024\n- returns calendar availability for 2024 - Resource Templates - dynamic URIs with parameters for flexible queries. Example:\ntravel://activities/{city}/{category}\n- returns activities by city and categorytravel://activities/barcelona/museums\n- returns all museums in Barcelona\nExample: Getting Travel Planning Context\nContinuing with the travel planning example, resources provide the AI application with access to relevant information:- Calendar data (\ncalendar://events/2024\n) - Checks user availability - Travel documents (\nfile:///Documents/Travel/passport.pdf\n) - Accesses important documents - Previous itineraries (\ntrips://history/barcelona-2023\n) - References past trips and preferences\norigin\nairport and begins to input “Bar” as the destination\nairport, the system can suggest “Barcelona (BCN)” or “Barbados (BGI)”.\nParameter Completion\nDynamic resources support parameter completion. For example:- Typing “Par” as input for\nweather://forecast/{city}\nmight suggest “Paris” or “Park City” - Typing “JFK” for\nflights://search/{airport}\nmight suggest “JFK - John F. Kennedy International”\nUser Interaction Model\nResources are application-driven, giving them flexibility in how they retrieve, process, and present available context. Common interaction patterns include:- Tree or list views for browsing resources in familiar folder-like structures\n- Search and filter interfaces for finding specific resources\n- Automatic context inclusion or smart suggestions based on heuristics or AI selection\n- Manual or bulk selection interfaces for including single or multiple resources\nPrompts\nPrompts provide reusable templates. They allow MCP server authors to provide parameterized prompts for a domain, or showcase how to best use the MCP server.How Prompts Work\nPrompts are structured templates that define expected inputs and interaction patterns. They are user-controlled, requiring explicit invocation rather than automatic triggering. Prompts can be context-aware, referencing available resources and tools to create comprehensive workflows. Similar to resources, prompts support parameter completion to help users discover valid argument values. Protocol operations:Example: Streamlined Workflows\nPrompts provide structured templates for common tasks. In the travel planning context: “Plan a vacation” prompt:- Selection of the “Plan a vacation” template\n- Structured input: Barcelona, 7 days, $3000, [“beaches”, “architecture”, “food”]\n- Consistent workflow execution based on the template\nUser Interaction Model\nPrompts are user-controlled, requiring explicit invocation. The protocol gives implementers freedom to design interfaces that feel natural within their application. Key principles include:- Easy discovery of available prompts\n- Clear descriptions of what each prompt does\n- Natural argument input with validation\n- Transparent display of the prompt’s underlying template\n- Slash commands (typing ”/” to see available prompts like /plan-vacation)\n- Command palettes for searchable access\n- Dedicated UI buttons for frequently used prompts\n- Context menus that suggest relevant prompts\nBringing Servers Together\nThe real power of MCP emerges when multiple servers work together, combining their specialized capabilities through a unified interface.Example: Multi-Server Travel Planning\nConsider a personalized AI travel planner application, with three connected servers:- Travel Server - Handles flights, hotels, and itineraries\n- Weather Server - Provides climate data and forecasts\n- Calendar/Email Server - Manages schedules and communications\nThe Complete Flow\n-\nUser invokes a prompt with parameters:\n-\nUser selects resources to include:\ncalendar://my-calendar/June-2024\n(from Calendar Server)travel://preferences/europe\n(from Travel Server)travel://past-trips/Spain-2023\n(from Travel Server)\n-\nAI processes the request using tools:\nThe AI first reads all selected resources to gather context - identifying available dates from the calendar, learning preferred airlines and hotel types from travel preferences, and discovering previously enjoyed locations from past trips.\nUsing this context, the AI then executes a series of Tools:\nsearchFlights()\n- Queries airlines for NYC to Barcelona flightscheckWeather()\n- Retrieves climate forecasts for travel dates\nbookHotel()\n- Finds hotels within the specified budgetcreateCalendarEvent()\n- Adds the trip to the user’s calendarsendEmail()\n- Sends confirmation with trip details",
"updated_at": ""
},
{
"id": "doc_modelcontextprotocol.io_docs_learn_client-concepts_4478ec6d",
"url": "https://modelcontextprotocol.io/docs/learn/client-concepts",
"title": "Understanding MCP clients - Model Context Protocol",
"content": "Core Client Features\nIn addition to making use of context provided by servers, clients may provide several features to servers. These client features allow server authors to build richer interactions.Elicitation\nElicitation enables servers to request specific information from users during interactions, creating more dynamic and responsive workflows.Overview\nElicitation provides a structured way for servers to gather necessary information on demand. Instead of requiring all information up front or failing when data is missing, servers can pause their operations to request specific inputs from users. This creates more flexible interactions where servers adapt to user needs rather than following rigid patterns. Elicitation flow: The flow enables dynamic information gathering. Servers can request specific data when needed, users provide information through appropriate UI, and servers continue processing with the newly acquired context. Elicitation components example:Example: Holiday Booking Approval\nA travel booking server demonstrates elicitation’s power through the final booking confirmation process. When a user has selected their ideal vacation package to Barcelona, the server needs to gather final approval and any missing details before proceeding. The server elicits booking confirmation with a structured request that includes the trip summary (Barcelona flights June 15-22, beachfront hotel, total $3,000) and fields for any additional preferences—such as seat selection, room type, or travel insurance options. As the booking progresses, the server elicits contact information needed to complete the reservation. It might ask for traveler details for flight bookings, special requests for the hotel, or emergency contact information.User Interaction Model\nElicitation interactions are designed to be clear, contextual, and respectful of user autonomy: Request presentation: Clients display elicitation requests with clear context about which server is asking, why the information is needed, and how it will be used. The request message explains the purpose while the schema provides structure and validation. Response options: Users can provide the requested information through appropriate UI controls (text fields, dropdowns, checkboxes), decline to provide information with optional explanation, or cancel the entire operation. Clients validate responses against the provided schema before returning them to servers. Privacy considerations: Elicitation never requests passwords or API keys. Clients warn about suspicious requests and let users review data before sending.Roots\nRoots define filesystem boundaries for server operations, allowing clients to specify which directories servers should focus on.Overview\nRoots are a mechanism for clients to communicate filesystem access boundaries to servers. They consist of file URIs that indicate directories where servers can operate, helping servers understand the scope of available files and folders. While roots communicate intended boundaries, they do not enforce security restrictions. Actual security must be enforced at the operating system level, via file permissions and/or sandboxing. Root structure:file://\nURI scheme. They help servers understand project boundaries, workspace organization, and accessible directories. The roots list can be updated dynamically as users work with different projects or folders, with servers receiving notifications through roots/list_changed\nwhen boundaries change.\nExample: Travel Planning Workspace\nA travel agent working with multiple client trips benefits from roots to organize filesystem access. Consider a workspace with different directories for various aspects of travel planning. The client provides filesystem roots to the travel planning server:file:///Users/agent/travel-planning\n- Main workspace containing all travel filesfile:///Users/agent/travel-templates\n- Reusable itinerary templates and resourcesfile:///Users/agent/client-documents\n- Client passports and travel documents\nfile:///Users/agent/archive/2023-trips\n, the client updates the roots list via roots/list_changed\n.\nFor a complete implementation of a server that respects roots, see the filesystem server in the official servers repository.\nDesign Philosophy\nRoots serve as a coordination mechanism between clients and servers, not a security boundary. The specification requires that servers “SHOULD respect root boundaries,” and not that they “MUST enforce” them, because servers run code the client cannot control. Roots work best when servers are trusted or vetted, users understand their advisory nature, and the goal is preventing accidents rather than stopping malicious behavior. They excel at context scoping (telling servers where to focus), accident prevention (helping well-behaved servers stay in bounds), and workflow organization (such as managing project boundaries automatically).User Interaction Model\nRoots are typically managed automatically by host applications based on user actions, though some applications may expose manual root management: Automatic root detection: When users open folders, clients automatically expose them as roots. Opening a travel workspace allows the client to expose that directory as a root, helping servers understand which itineraries and documents are in scope for the current work. Manual root configuration: Advanced users can specify roots through configuration. For example, adding/travel-templates\nfor reusable resources while excluding directories with financial records.\nSampling\nSampling allows servers to request language model completions through the client, enabling agentic behaviors while maintaining security and user control.Overview\nSampling enables servers to perform AI-dependent tasks without directly integrating with or paying for AI models. Instead, servers can request that the client—which already has AI model access—handle these tasks on their behalf. This approach puts the client in complete control of user permissions and security measures. Because sampling requests occur within the context of other operations—like a tool analyzing data—and are processed as separate model calls, they maintain clear boundaries between different contexts, allowing for more efficient use of the context window. Sampling flow: The flow ensures security through multiple human-in-the-loop checkpoints. Users review and can modify both the initial request and the generated response before it returns to the server. Request parameters example:Example: Flight Analysis Tool\nConsider a travel booking server with a tool calledfindBestFlight\nthat uses sampling to analyze available flights and recommend the optimal choice. When a user asks “Book me the best flight to Barcelona next month,” the tool needs AI assistance to evaluate complex trade-offs.\nThe tool queries airline APIs and gathers 47 flight options. It then requests AI assistance to analyze these options: “Analyze these flight options and recommend the best choice: [47 flights with prices, times, airlines, and layovers] User preferences: morning departure, max 1 layover.”\nThe client initiates the sampling request, allowing the AI to evaluate trade-offs—like cheaper red-eye flights versus convenient morning departures. The tool uses this analysis to present the top three recommendations.",
"updated_at": ""
},
{
"id": "doc_modelcontextprotocol.io_specification_versioning_9112eed6",
"url": "https://modelcontextprotocol.io/specification/versioning",
"title": "Versioning - Model Context Protocol",
"content": "YYYY-MM-DD\n, to indicate the last date backwards incompatible changes were made.\nThe protocol version will not be incremented when the\nprotocol is updated, as long as the changes maintain backwards compatibility. This allows\nfor incremental improvements while preserving interoperability.\nRevisions\nRevisions may be marked as:- Draft: in-progress specifications, not yet ready for consumption.\n- Current: the current protocol version, which is ready for use and may continue to receive backwards compatible changes.\n- Final: past, complete specifications that will not be changed.",
"updated_at": ""
},
{
"id": "doc_modelcontextprotocol.io_docs_develop_connect-local-servers_9d1b0564",
"url": "https://modelcontextprotocol.io/docs/develop/connect-local-servers",
"title": "Connect to local MCP servers - Model Context Protocol",
"content": "Prerequisites\nBefore starting this tutorial, ensure you have the following installed on your system:Claude Desktop\nDownload and install Claude Desktop for your operating system. Claude Desktop is available for macOS and Windows. If you already have Claude Desktop installed, verify you’re running the latest version by clicking the Claude menu and selecting “Check for Updates…”Node.js\nThe Filesystem Server and many other MCP servers require Node.js to run. Verify your Node.js installation by opening a terminal or command prompt and running:Understanding MCP Servers\nMCP servers are programs that run on your computer and provide specific capabilities to Claude Desktop through a standardized protocol. Each server exposes tools that Claude can use to perform actions, with your approval. The Filesystem Server we’ll install provides tools for:- Reading file contents and directory structures\n- Creating new files and directories\n- Moving and renaming files\n- Searching for files by name or content\nInstalling the Filesystem Server\nThe process involves configuring Claude Desktop to automatically start the Filesystem Server whenever you launch the application. This configuration is done through a JSON file that tells Claude Desktop which servers to run and how to connect to them.1\nOpen Claude Desktop Settings\nStart by accessing the Claude Desktop settings. Click on the Claude menu in your system’s menu bar (not the settings within the Claude window itself) and select “Settings…”On macOS, this appears in the top menu bar:This opens the Claude Desktop configuration window, which is separate from your Claude account settings.\n2\nAccess Developer Settings\nIn the Settings window, navigate to the “Developer” tab in the left sidebar. This section contains options for configuring MCP servers and other developer features.Click the “Edit Config” button to open the configuration file:This action creates a new configuration file if one doesn’t exist, or opens your existing configuration. The file is located at:\n- macOS:\n~/Library/Application Support/Claude/claude_desktop_config.json\n- Windows:\n%APPDATA%\\Claude\\claude_desktop_config.json\n3\nConfigure the Filesystem Server\nReplace the contents of the configuration file with the following JSON structure. This configuration tells Claude Desktop to start the Filesystem Server with access to specific directories:Replace\nusername\nwith your actual computer username. The paths listed in the args\narray specify which directories the Filesystem Server can access. You can modify these paths or add additional directories as needed.Understanding the Configuration\n\"filesystem\"\n: A friendly name for the server that appears in Claude Desktop\"command\": \"npx\"\n: Uses Node.js’s npx tool to run the server\"-y\"\n: Automatically confirms the installation of the server package\"@modelcontextprotocol/server-filesystem\"\n: The package name of the Filesystem Server- The remaining arguments: Directories the server is allowed to access\nSecurity ConsiderationOnly grant access to directories you’re comfortable with Claude reading and modifying. The server runs with your user account permissions, so it can perform any file operations you can perform manually.\n4\nRestart Claude Desktop\nAfter saving the configuration file, completely quit Claude Desktop and restart it. The application needs to restart to load the new configuration and start the MCP server.Upon successful restart, you’ll see an MCP server indicator in the bottom-right corner of the conversation input box:Click on this indicator to view the available tools provided by the Filesystem Server:If the server indicator doesn’t appear, refer to the Troubleshooting section for debugging steps.\nUsing the Filesystem Server\nWith the Filesystem Server connected, Claude can now interact with your file system. Try these example requests to explore the capabilities:File Management Examples\n- “Can you write a poem and save it to my desktop?” - Claude will compose a poem and create a new text file on your desktop\n- “What work-related files are in my downloads folder?” - Claude will scan your downloads and identify work-related documents\n- “Please organize all images on my desktop into a new folder called ‘Images’” - Claude will create a folder and move image files into it\nHow Approval Works\nBefore executing any file system operation, Claude will request your approval. This ensures you maintain control over all actions:Troubleshooting\nIf you encounter issues setting up or using the Filesystem Server, these solutions address common problems:Server not showing up in Claude / hammer icon missing\nServer not showing up in Claude / hammer icon missing\n- Restart Claude Desktop completely\n- Check your\nclaude_desktop_config.json\nfile syntax - Make sure the file paths included in\nclaude_desktop_config.json\nare valid and that they are absolute and not relative - Look at logs to see why the server is not connecting\n- In your command line, try manually running the server (replacing\nusername\nas you did inclaude_desktop_config.json\n) to see if you get any errors:\nGetting logs from Claude Desktop\nGetting logs from Claude Desktop\nClaude.app logging related to MCP is written to log files in:\n-\nmacOS:\n~/Library/Logs/Claude\n-\nWindows:\n%APPDATA%\\Claude\\logs\n-\nmcp.log\nwill contain general logging about MCP connections and connection failures. -\nFiles named\nmcp-server-SERVERNAME.log\nwill contain error (stderr) logging from the named server.\nTool calls failing silently\nTool calls failing silently\nIf Claude attempts to use the tools but they fail:\n- Check Claude’s logs for errors\n- Verify your server builds and runs without errors\n- Try restarting Claude Desktop\nNone of this is working. What do I do?\nNone of this is working. What do I do?\nPlease refer to our debugging guide for better debugging tools and more detailed guidance.\nENOENT error and `${APPDATA}` in paths on Windows\nENOENT error and `${APPDATA}` in paths on Windows\nIf your configured server fails to load, and you see within its logs an error referring to With this change in place, launch Claude Desktop once again.\n${APPDATA}\nwithin a path, you may need to add the expanded value of %APPDATA%\nto your env\nkey in claude_desktop_config.json\n:NPM should be installed globallyThe\nnpx\ncommand may continue to fail if you have not installed NPM globally. If NPM is already installed globally, you will find %APPDATA%\\npm\nexists on your system. If not, you can install NPM globally by running the following command:Next Steps\nNow that you’ve successfully connected Claude Desktop to a local MCP server, explore these options to expand your setup:Explore other servers\nBrowse our collection of official and community-created MCP servers for\nadditional capabilities\nBuild your own server\nCreate custom MCP servers tailored to your specific workflows and\nintegrations\nConnect to remote servers\nLearn how to connect Claude to remote MCP servers for cloud-based tools and\nservices\nUnderstand the protocol\nDive deeper into how MCP works and its architecture",
"updated_at": ""
},
{
"id": "doc_modelcontextprotocol.io_docs_develop_connect-remote-servers_72775276",
"url": "https://modelcontextprotocol.io/docs/develop/connect-remote-servers",
"title": "Connect to remote MCP Servers - Model Context Protocol",
"content": "Understanding Remote MCP Servers\nRemote MCP servers function similarly to local MCP servers but are hosted on the internet rather than your local machine. They expose tools, prompts, and resources that Claude can use to perform tasks on your behalf. These servers can integrate with various services such as project management tools, documentation systems, code repositories, and any other API-enabled service. The key advantage of remote MCP servers is their accessibility. Unlike local servers that require installation and configuration on each device, remote servers are available from any MCP client with an internet connection. This makes them ideal for web-based AI applications, integrations that emphasize ease-of-use and services that require server-side processing or authentication.What are Custom Connectors?\nCustom Connectors serve as the bridge between Claude and remote MCP servers. They allow you to connect Claude directly to the tools and data sources that matter most to your workflows, enabling Claude to operate within your favorite software and draw insights from the complete context of your external tools. With Custom Connectors, you can:- Connect Claude to existing remote MCP servers provided by third-party developers\n- Build your own remote MCP servers to connect with any tool\nConnecting to a Remote MCP Server\nThe process of connecting Claude to a remote MCP server involves adding a Custom Connector through the Claude interface. This establishes a secure connection between Claude and your chosen remote server.1\nNavigate to Connector Settings\nOpen Claude in your browser and navigate to the settings page. You can access this by clicking on your profile icon and selecting “Settings” from the dropdown menu. Once in settings, locate and click on the “Connectors” section in the sidebar.This will display your currently configured connectors and provide options to add new ones.\n2\nAdd a Custom Connector\nIn the Connectors section, scroll to the bottom where you’ll find the “Add custom connector” button. Click this button to begin the connection process.A dialog will appear prompting you to enter the remote MCP server URL. This URL should be provided by the server developer or administrator. Enter the complete URL, ensuring it includes the proper protocol (https://) and any necessary path components.After entering the URL, click “Add” to proceed with the connection.\n3\nComplete Authentication\nMost remote MCP servers require authentication to ensure secure access to their resources. The authentication process varies depending on the server implementation but commonly involves OAuth, API keys, or username/password combinations.Follow the authentication prompts provided by the server. This may redirect you to a third-party authentication provider or display a form within Claude. Once authentication is complete, Claude will establish a secure connection to the remote server.\n4\nAccess Resources and Prompts\nAfter successful connection, the remote server’s resources and prompts become available in your Claude conversations. You can access these by clicking the paperclip icon in the message input area, which opens the attachment menu.The menu displays all available resources and prompts from your connected servers. Select the items you want to include in your conversation. These resources provide Claude with context and information from your external tools.\n5\nConfigure Tool Permissions\nRemote MCP servers often expose multiple tools with varying capabilities. You can control which tools Claude is allowed to use by configuring permissions in the connector settings. This ensures Claude only performs actions you’ve explicitly authorized.Navigate back to the Connectors settings and click on your connected server. Here you can enable or disable specific tools, set usage limits, and configure other security parameters according to your needs.\nBest Practices for Using Remote MCP Servers\nWhen working with remote MCP servers, consider these recommendations to ensure a secure and efficient experience: Security considerations: Always verify the authenticity of remote MCP servers before connecting. Only connect to servers from trusted sources, and review the permissions requested during authentication. Be cautious about granting access to sensitive data or systems. Managing multiple connectors: You can connect to multiple remote MCP servers simultaneously. Organize your connectors by purpose or project to maintain clarity. Regularly review and remove connectors you no longer use to keep your workspace organized and secure.Next Steps\nNow that you’ve connected Claude to a remote MCP server, you can explore its capabilities in your conversations. Try using the connected tools to automate tasks, access external data, or integrate with your existing workflows.Build your own remote server\nCreate custom remote MCP servers to integrate with proprietary tools and\nservices\nExplore available servers\nBrowse our collection of official and community-created MCP servers\nConnect local servers\nLearn how to connect Claude Desktop to local MCP servers for direct system\naccess\nUnderstand the architecture\nDive deeper into how MCP works and its architecture",
"updated_at": ""
},
{
"id": "doc_modelcontextprotocol.io_docs_develop_build-server_97df5a7a",
"url": "https://modelcontextprotocol.io/docs/develop/build-server",
"title": "Build an MCP server - Model Context Protocol",
"content": "What we’ll be building\nWe’ll build a server that exposes two tools:get_alerts\nand get_forecast\n. Then we’ll connect the server to an MCP host (in this case, Claude for Desktop):\nServers can connect to any client. We’ve chosen Claude for Desktop here for simplicity, but we also have guides on building your own client as well as a list of other clients here.\nCore MCP Concepts\nMCP servers can provide three main types of capabilities:- Resources: File-like data that can be read by clients (like API responses or file contents)\n- Tools: Functions that can be called by the LLM (with user approval)\n- Prompts: Pre-written templates that help users accomplish specific tasks\n- Python\n- Node\n- Java\n- Kotlin\n- C#\nLet’s get started with building our weather server! You can find the complete code for what we’ll be building here.Make sure to restart your terminal afterwards to ensure that the Now let’s dive into building your server.The FastMCP class uses Python type hints and docstrings to automatically generate tool definitions, making it easy to create and maintain MCP tools.Your server is complete! Run First, make sure you have Claude for Desktop installed. You can install the latest version\nhere. If you already have Claude for Desktop, make sure it’s updated to the latest version.We’ll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at You’ll then add your servers in the This tells Claude for Desktop:\nPrerequisite knowledge\nThis quickstart assumes you have familiarity with:- Python\n- LLMs like Claude\nLogging in MCP Servers\nWhen implementing MCP servers, be careful about how you handle logging:For STDIO-based servers: Never write to standard output (stdout). This includes:print()\nstatements in Pythonconsole.log()\nin JavaScriptfmt.Println()\nin Go- Similar stdout functions in other languages\nBest Practices\n- Use a logging library that writes to stderr or files.\n- Tool names should follow the format specified here.\nQuick Examples\nSystem requirements\n- Python 3.10 or higher installed.\n- You must use the Python MCP SDK 1.2.0 or higher.\nSet up your environment\nFirst, let’s installuv\nand set up our Python project and environment:uv\ncommand gets picked up.Now, let’s create and set up our project:Building your server\nImporting packages and setting up the instance\nAdd these to the top of yourweather.py\n:Helper functions\nNext, let’s add our helper functions for querying and formatting the data from the National Weather Service API:Implementing tool execution\nThe tool execution handler is responsible for actually executing the logic of each tool. Let’s add it:Running the server\nFinally, let’s initialize and run the server:uv run weather.py\nto start the MCP server, which will listen for messages from MCP hosts.Let’s now test your server from an existing MCP host, Claude for Desktop.Testing your server with Claude for Desktop\nClaude for Desktop is not yet available on Linux. Linux users can proceed to the Building a client tutorial to build an MCP client that connects to the server we just built.\n~/Library/Application Support/Claude/claude_desktop_config.json\nin a text editor. Make sure to create the file if it doesn’t exist.For example, if you have VS Code installed:mcpServers\nkey. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.In this case, we’ll add our single weather server like so:You may need to put the full path to the\nuv\nexecutable in the command\nfield. You can get this by running which uv\non macOS/Linux or where uv\non Windows.Make sure you pass in the absolute path to your server. You can get this by running\npwd\non macOS/Linux or cd\non Windows Command Prompt. On Windows, remember to use double backslashes (\\\\\n) or forward slashes (/\n) in the JSON path.- There’s an MCP server named “weather”\n- To launch it by running\nuv --directory /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather run weather.py\nTest with commands\nLet’s make sure Claude for Desktop is picking up the two tools we’ve exposed in ourweather\nserver. You can do this by looking for the “Search and tools” icon:\n- What’s the weather in Sacramento?\n- What are the active weather alerts in Texas?\nSince this is the US National Weather service, the queries will only work for US locations.\nWhat’s happening under the hood\nWhen you ask a question:- The client sends your question to Claude\n- Claude analyzes the available tools and decides which one(s) to use\n- The client executes the chosen tool(s) through the MCP server\n- The results are sent back to Claude\n- Claude formulates a natural language response\n- The response is displayed to you!\nTroubleshooting\nClaude for Desktop Integration Issues\nClaude for Desktop Integration Issues\nGetting logs from Claude for DesktopClaude.app logging related to MCP is written to log files in Server not showing up in ClaudeTool calls failing silentlyIf Claude attempts to use the tools but they fail:\n~/Library/Logs/Claude\n:mcp.log\nwill contain general logging about MCP connections and connection failures.- Files named\nmcp-server-SERVERNAME.log\nwill contain error (stderr) logging from the named server.\n- Check your\nclaude_desktop_config.json\nfile syntax - Make sure the path to your project is absolute and not relative\n- Restart Claude for Desktop completely\nTo properly restart Claude for Desktop, you must fully quit the application:\n- Windows: Right-click the Claude icon in the system tray (which may be hidden in the “hidden icons” menu) and select “Quit” or “Exit”.\n- macOS: Use Cmd+Q or select “Quit Claude” from the menu bar.\n- Check Claude’s logs for errors\n- Verify your server builds and runs without errors\n- Try restarting Claude for Desktop\nWeather API Issues\nWeather API Issues\nError: Failed to retrieve grid point dataThis usually means either:\n- The coordinates are outside the US\n- The NWS API is having issues\n- You’re being rate limited\n- Verify you’re using US coordinates\n- Add a small delay between requests\n- Check the NWS API status page\nFor more advanced troubleshooting, check out our guide on Debugging MCP\nNext steps\nBuilding a client\nLearn how to build your own MCP client that can connect to your server\nExample servers\nCheck out our gallery of official MCP servers and implementations\nDebugging Guide\nLearn how to effectively debug MCP servers and integrations\nBuilding MCP with LLMs\nLearn how to use LLMs like Claude to speed up your MCP development",
"updated_at": ""
},
{
"id": "doc_modelcontextprotocol.io_docs_develop_build-client_8ee5d0e4",
"url": "https://modelcontextprotocol.io/docs/develop/build-client",
"title": "Build an MCP client - Model Context Protocol",
"content": "- Python\n- Node\n- Java\n- Kotlin\n- C#\nYou can find the complete code for this tutorial here.Add You can find the complete The client will:\nSystem Requirements\nBefore starting, ensure your system meets these requirements:- Mac or Windows computer\n- Latest Python version installed\n- Latest version of\nuv\ninstalled\nSetting Up Your Environment\nFirst, create a new Python project withuv\n:Setting Up Your API Key\nYou’ll need an Anthropic API key from the Anthropic Console.Create a.env\nfile to store it:.env\nto your .gitignore\n:Make sure you keep your\nANTHROPIC_API_KEY\nsecure!Creating the Client\nBasic Client Structure\nFirst, let’s set up our imports and create the basic client class:Server Connection Management\nNext, we’ll implement the method to connect to an MCP server:Query Processing Logic\nNow let’s add the core functionality for processing queries and handling tool calls:Interactive Chat Interface\nNow we’ll add the chat loop and cleanup functionality:Main Entry Point\nFinally, we’ll add the main execution logic:client.py\nfile here.Key Components Explained\n1. Client Initialization\n- The\nMCPClient\nclass initializes with session management and API clients - Uses\nAsyncExitStack\nfor proper resource management - Configures the Anthropic client for Claude interactions\n2. Server Connection\n- Supports both Python and Node.js servers\n- Validates server script type\n- Sets up proper communication channels\n- Initializes the session and lists available tools\n3. Query Processing\n- Maintains conversation context\n- Handles Claude’s responses and tool calls\n- Manages the message flow between Claude and tools\n- Combines results into a coherent response\n4. Interactive Interface\n- Provides a simple command-line interface\n- Handles user input and displays responses\n- Includes basic error handling\n- Allows graceful exit\n5. Resource Management\n- Proper cleanup of resources\n- Error handling for connection issues\n- Graceful shutdown procedures\nCommon Customization Points\n-\nTool Handling\n- Modify\nprocess_query()\nto handle specific tool types - Add custom error handling for tool calls\n- Implement tool-specific response formatting\n- Modify\n-\nResponse Processing\n- Customize how tool results are formatted\n- Add response filtering or transformation\n- Implement custom logging\n-\nUser Interface\n- Add a GUI or web interface\n- Implement rich console output\n- Add command history or auto-completion\nRunning the Client\nTo run your client with any MCP server:If you’re continuing the weather tutorial from the server quickstart, your command might look something like this:\npython client.py .../quickstart-resources/weather-server-python/weather.py\n- Connect to the specified server\n- List available tools\n- Start an interactive chat session where you can:\n- Enter queries\n- See tool executions\n- Get responses from Claude\nHow It Works\nWhen you submit a query:- The client gets the list of available tools from the server\n- Your query is sent to Claude along with tool descriptions\n- Claude decides which tools (if any) to use\n- The client executes any requested tool calls through the server\n- Results are sent back to Claude\n- Claude provides a natural language response\n- The response is displayed to you\nBest practices\n-\nError Handling\n- Always wrap tool calls in try-catch blocks\n- Provide meaningful error messages\n- Gracefully handle connection issues\n-\nResource Management\n- Use\nAsyncExitStack\nfor proper cleanup - Close connections when done\n- Handle server disconnections\n- Use\n-\nSecurity\n- Store API keys securely in\n.env\n- Validate server responses\n- Be cautious with tool permissions\n- Store API keys securely in\n-\nTool Names\n- Tool names can be validated according to the format specified here\n- If a tool name conforms to the specified format, it should not fail validation by an MCP client\nTroubleshooting\nServer Path Issues\n- Double-check the path to your server script is correct\n- Use the absolute path if the relative path isn’t working\n- For Windows users, make sure to use forward slashes (/) or escaped backslashes (\\) in the path\n- Verify the server file has the correct extension (.py for Python or .js for Node.js)\nResponse Timing\n- The first response might take up to 30 seconds to return\n- This is normal and happens while:\n- The server initializes\n- Claude processes the query\n- Tools are being executed\n- Subsequent responses are typically faster\n- Don’t interrupt the process during this initial waiting period\nCommon Error Messages\nIf you see:FileNotFoundError\n: Check your server pathConnection refused\n: Ensure the server is running and the path is correctTool execution failed\n: Verify the tool’s required environment variables are setTimeout error\n: Consider increasing the timeout in your client configuration",
"updated_at": ""
},
{
"id": "doc_modelcontextprotocol.io_docs_tutorials_security_authorization_47230774",
"url": "https://modelcontextprotocol.io/docs/tutorials/security/authorization",
"title": "Understanding Authorization in MCP - Model Context Protocol",
"content": "When Should You Use Authorization?\nWhile authorization for MCP servers is optional, it is strongly recommended when:- Your server accesses user-specific data (emails, documents, databases)\n- You need to audit who performed which actions\n- Your server grants access to its APIs that require user consent\n- You’re building for enterprise environments with strict access controls\n- You want to implement rate limiting or usage tracking per user\nAuthorization for Local MCP ServersFor MCP servers using the STDIO transport, you can use environment-based credentials or credentials provided by third-party libraries embedded directly in the MCP server instead. Because a STDIO-built MCP server runs locally, it has access to a range of flexible options when it comes to acquiring user credentials that may or may not rely on in-browser authentication and authorization flows.OAuth flows, in turn, are designed for HTTP-based transports where the MCP server is remotely-hosted and the client uses OAuth to establish that a user is authorized to access said remote server.\nThe Authorization Flow: Step by Step\nLet’s walk through what happens when a client wants to connect to your protected MCP server:1\nInitial Handshake\nWhen your MCP client first tries to connect, your server responds with a This tells the client that authorization is required for the MCP server and where to get the necessary information to kickstart the authorization flow.\n401 Unauthorized\nand tells the client where to find authorization information, captured in a Protected Resource Metadata (PRM) document. The document is hosted by the MCP server, follows a predictable path pattern, and is provided to the client in the resource_metadata\nparameter within the WWW-Authenticate\nheader.2\nProtected Resource Metadata Discovery\nWith the URI pointer to the PRM document, the client will fetch the metadata to learn about the authorization server, supported scopes, and other resource information. The data is typically encapsulated in a JSON blob, similar to the one below.You can see a more comprehensive example in RFC 9278 Section 3.2.\n3\nAuthorization Server Discovery\nNext, the client discovers what the authorization server can do by fetching its metadata. If the PRM document lists more than one authorization server, the client can decide which one to use.With an authorization server selected, the client will then construct a standard metadata URI and issue a request to the OpenID Connect (OIDC) Discovery or OAuth 2.0 Auth Server Metadata endpoints (depending on authorization server support)\nand retrieve another set of metadata properties that will allow it to know the endpoints it needs to complete the authorization flow.\n4\nClient Registration\nWith all the metadata out of the way, the client now needs to make sure that it’s registered with the authorization server. This can be done in two ways.First, the client can be pre-registered with a given authorization server, in which case it can have embedded client registration information that it uses to complete the authorization flow.Alternatively, the client can use Dynamic Client Registration (DCR) to dynamically register itself with the authorization server. The latter scenario requires the authorization server to support DCR. If the authorization server does support DCR, the client will send a request to the If the registration succeeds, the authorization server will return a JSON blob with client registration information.\nregistration_endpoint\nwith its information:No DCR or Pre-RegistrationIn case a MCP client connects to a MCP server that doesn’t use an authorization server that supports DCR and the client is not pre-registered with said authorization server, it’s the responsibility of the client developer to provide an affordance for the end-user to enter client information manually.\n5\nUser Authorization\nThe client will now need to open a browser to the The access token is what the client will use to authenticate requests to the MCP server. This step follows standard OAuth 2.1 authorization code with PKCE conventions.\n/authorize\nendpoint, where the user can log in and grant the required permissions. The authorization server will then redirect back to the client with an authorization code that the client exchanges for tokens:6\nMaking Authenticated Requests\nFinally, the client can make requests to your MCP server using the access token embedded in the The MCP server will need to validate the token and process the request if the token is valid and has the required permissions.\nAuthorization\nheader:Implementation Example\nTo get started with a practical implementation, we will use a Keycloak authorization server hosted in a Docker container. Keycloak is an open-source authorization server that can be easily deployed locally for testing and experimentation. Make sure that you download and install Docker Desktop. We will need it to deploy Keycloak on our development machine.Keycloak Setup\nFrom your terminal application, run the following command to start the Keycloak container:8080\nand have an admin\nuser with admin\npassword.\nNot for ProductionThe configuration above may be suitable for testing and experimentation; however, you should never use it in production. Refer to the Configuring Keycloak for production guide for additional details on how to deploy the authorization server for scenarios that require reliability, security, and high availability.\nhttp://localhost:8080\n.\nmcp:tools\nscope. We will use this to access all of the tools on our MCP server.\nmcp:tools\nclient scope and click on Mappers, followed by Configure a new mapper. Select Audience.\naudience-config\n. Add a value for Included Custom Audience, set to http://localhost:3000\n. This will be the URI of our test server.\nNot for ProductionThe audience configuration above is meant for testing. For production scenarios, additional set-up and configuration will be required to ensure that audiences are properly constrained for issued tokens. Specifically, the audience needs to be based on the resource parameter passed from the client, not a fixed value.\nifconfig\ncommand on Linux or macOS, or ipconfig\non Windows. You can see the IP address you need to add by looking at the keycloak logs for a line that looks like Failed to verify remote host : 192.168.215.1\n. Check that the IP address is associated with your host. This may be for a bridge network depending on your docker setup.\nGetting the HostIf you are running Keycloak from a container, you will also be able to see the host IP from the Terminal in the container logs.\n- Go to Clients.\n- Click Create client.\n- Give your client a unique Client ID and click Next.\n- Enable Client authentication and click Next.\n- Click Save.\nHandling SecretsNever embed client credentials directly in your code. We recommend using environment variables or specialized solutions for secret storage.\nEmbedded AudienceNotice the\naud\nclaim embedded in the token - it’s currently set to be the URI of the test MCP server and it’s inferred from the scope that we’ve previously configured. This will be important in our implementation to validate.MCP Server Setup\nWe will now set up our MCP server to use the locally-running Keycloak authorization server. Depending on your programming language preference, you can use one of the supported MCP SDKs. For our testing purposes, we will create an extremely simple MCP server that exposes two tools - one for addition and another for multiplication. The server will require authorization to access these.- TypeScript\n- Python\n- C#\nYou can see the complete TypeScript project in the sample repository.Prior to running the code below, ensure that you have a When you run the server, you can add it to your MCP client, such as Visual Studio Code, by providing the MCP server endpoint.For more details about implementing MCP servers in TypeScript, refer to the TypeScript SDK documentation.\n.env\nfile with the following content:OAUTH_CLIENT_ID\nand OAUTH_CLIENT_SECRET\nare associated with the MCP server client we created earlier.In addition to implementing the MCP authorization specification, the server below also does token introspection via Keycloak to make sure that the token it receives from the client is valid. It also implements basic logging to allow you to easily diagnose any issues.Testing the MCP Server\nFor testing purposes, we will be using Visual Studio Code, but any client that supports MCP and the new authorization specification will fit. Press Cmd + Shift + P and select MCP: Add server…. Select HTTP and enterhttp://localhost:3000\n. Give the server a unique name to be used inside Visual Studio Code. In mcp.json\nyou should now see an entry like this:\nmcp:tools\nscope.\nmcp.json\n.\n#\nsign in the chat view.\nCommon Pitfalls and How to Avoid Them\nFor comprehensive security guidance, including attack vectors, mitigation strategies, and implementation best practices, make sure to read through Security Best Practices. A few key issues are called out below.- Do not implement token validation or authorization logic by yourself. Use off-the-shelf, well-tested, and secure libraries for things like token validation or authorization decisions. Doing everything from scratch means that you’re more likely to implement things incorrectly unless you are a security expert.\n- Use short-lived access tokens. Depending on the authorization server used, this setting might be customizable. We recommend to not use long-lived tokens - if a malicious actor steals them, they will be able to maintain their access for longer periods.\n- Always validate tokens. Just because your server received a token does not mean that the token is valid or that it’s meant for your server. Always verify that what your MCP server is getting from the client matches the required constraints.\n- Store tokens in secure, encrypted storage. In certain scenarios, you might need to cache tokens server-side. If that is the case, ensure that the storage has the right access controls and cannot be easily exfiltrated by malicious parties with access to your server. You should also implement robust cache eviction policies to ensure that your MCP server is not re-using expired or otherwise invalid tokens.\n- Enforce HTTPS in production. Do not accept tokens or redirect callbacks over plain HTTP except for\nlocalhost\nduring development. - Least-privilege scopes. Don’t use catch‑all scopes. Split access per tool or capability where possible and verify required scopes per route/tool on the resource server.\n- Don’t log credentials. Never log\nAuthorization\nheaders, tokens, codes, or secrets. Scrub query strings and headers. Redact sensitive fields in structured logs. - Separate app vs. resource server credentials. Don’t reuse your MCP server’s client secret for end‑user flows. Store all secrets in a proper secret manager, not in source control.\n- Return proper challenges. On 401, include\nWWW-Authenticate\nwithBearer\n,realm\n, andresource_metadata\nso clients can discover how to authenticate. - DCR (Dynamic Client Registration) controls. If enabled, be aware of constraints specific to your organization, such as trusted hosts, required vetting, and audited registrations. Unauthenticated DCR means that anyone can register any client with your authorization server.\n- Multi‑tenant/realm mix-ups. Pin to a single issuer/tenant unless explicitly multi‑tenant. Reject tokens from other realms even if signed by the same authorization server.\n- Audience/resource indicator misuse. Don’t configure or accept generic audiences (like\napi\n) or unrelated resources. Require the audience/resource to match your configured server. - Error detail leakage. Return generic messages to clients, but log detailed reasons with correlation IDs internally to aid troubleshooting without exposing internals.\n- Session identifier hardening. Treat\nMcp-Session-Id\nas untrusted input; never tie authorization to it. Regenerate on auth changes and validate lifecycle server‑side.\nRelated Standards and Documentation\nMCP authorization builds on these well-established standards:- OAuth 2.1: The core authorization framework\n- RFC 8414: Authorization Server Metadata discovery\n- RFC 7591: Dynamic Client Registration\n- RFC 9728: Protected Resource Metadata\n- RFC 8707: Resource Indicators",
"updated_at": ""
},
{
"id": "doc_modelcontextprotocol.io_docs_sdk_5f7c6714",
"url": "https://modelcontextprotocol.io/docs/sdk",
"title": "SDKs - Model Context Protocol",
"content": "Available SDKs\nGetting Started\nEach SDK provides the same functionality but follows the idioms and best practices of its language. All SDKs support:- Creating MCP servers that expose tools, resources, and prompts\n- Building MCP clients that can connect to any MCP server\n- Local and remote transport protocols\n- Protocol compliance with type safety",
"updated_at": ""
}
]
} |