SuperAPIAI Directory

mcp-go

github.com · AI developer platforms

mcp-go is a Go language implementation of the Model Context Protocol (MCP), used to establish standardized connections between LLM applications and external data sources and tools. It encapsulates protocol details and server management, providing a high-level, low-boilerplate interface covering core concepts such as Resources (static URIs and URI templates), Tools (including asynchronous task-based tools), and Prompts, and implements the MCP 2025-11-25 specification, with backward compatibility for 2025-06-18, 2025-03-26, and 2024-11-05. The transport layer supports stdio, SSE, and streamable-HTTP, and additionally provides capabilities such as session management, tool and prompt filtering, middleware, request hooks, OAuth protected resource metadata, CORS, DNS rebinding protection, and autocompletion. The project is under active development, and some advanced capabilities are still being refined.

Open website Alternatives
PricingOpen source开源项目(可免费自部署)

About this tool

Purpose and positioning mcp-go is a Go implementation of the Model Context Protocol (MCP), with the goal of enabling LLM applications to connect to external data and functionality in a secure, standardized way. It handles protocol details and server management, allowing developers to focus on building the tools themselves; the overall design pursues high-level interfaces, minimal code, and rapid development, building MCP servers with minimal boilerplate code. The project describes its goal as a complete implementation of the MCP core specification, while clearly stating that both the project and the MCP specification itself are under active development, with core functionality available and some advanced capabilities still in progress.

Core concepts and main capabilities The Server is the core interface of the MCP protocol, responsible for connection management, protocol compliance, and message routing. Resources are used to load information into the LLM context, similar to GET endpoints, supporting static fixed URIs and dynamic resources based on URI templates, and can implement multi-content returns and connect to databases or external APIs. Tools let the LLM perform actions through the server, similar to POST endpoints, and are suitable for producing computations and side effects, such as database queries, file operations, external API calls, and system operations; each tool should have a clear description, validate inputs, handle errors properly, return structured responses, and use appropriate result types. Prompts are reusable interaction templates that can include system instructions, required parameters, embedded resources, multiple messages, different content types (text, images, etc.), and custom URI schemes.

Task-based tools Task-based tools execute asynchronously and return results through polling, suitable for long-running operations that may block or time out. Three modes are supported: TaskSupportForbidden (default, cannot be invoked as a task), TaskSupportOptional (can be invoked synchronously or as a task), and TaskSupportRequired (must be invoked as a task). The execution flow is: the client invokes the tool with a task parameter, the server immediately returns a task ID, the tool executes asynchronously in the background, the client polls tasks/result to obtain the result, and the server sends a task status notification upon completion. WithMaxConcurrentTasks can be used to limit the number of concurrent tasks; once the limit is reached, new task creation requests will fail; completed, failed, or canceled tasks do not count toward the limit, and only tasks in the working state are counted; unspecified or set to 0 means no concurrency limit.

Sessions, hooks, and middleMiddleware Session management supports maintaining independent state for each connected client, registering and tracking client sessions, sending notifications to specific clients, and providing the ability to customize tools per session (implementing the SessionWithTools interface) as well as tool filtering. Session context is automatically passed to tool and resource handlers. The request lifecycle can hook callbacks via the Hooks object for telemetry and observability, such as counting malformed requests and logging the agent identity at initialization, added when creating the server via server.WithHooks. Tool call handlers support middleware (server.WithToolHandlerMiddleware), which takes effect on every tool call; server.WithRecovery can provide middleware that recovers from tool call panics. Prompt handlers likewise support middleware (server.WithPromptHandlerMiddleware, applied to every prompts/get) and prompt filtering (server.WithPromptFilter, applied to prompts/list results).

Autocompletion When a user fills in argument values for a prompt (identified by name) or a resource template (identified by URI), the server can provide contextual suggestions. This is enabled by using server.WithCompletions() when creating the server and implementing the interfaces corresponding to prompt arguments and resource template arguments. For prompts or resource templates with multiple arguments, the CompleteContext parameter provides access to previously completed arguments, allowing suggestions to be given based on earlier selections. When returning completion results, each response contains at most 100 items, using Total to indicate the total number of available matches and HasMore to indicate whether there are more results.

Transports and Deployment Three transport layers are supported: stdio, SSE, and streamable-HTTP. The SSE transport can use SetConnectionLostHandler() to detect and handle disconnections in order to implement reconnection logic. StreamableHTTPServer implements http.Handler and can be mounted on any net/http-based router; if the framework does not go through net/http (such as fasthttp or fiber), the transport-agnostic Handle entry point can be used to avoid buffering responses through an adapter. HTTPRequest is a plain struct containing Method, URL, Header, Body, and Context; HTTPResponseWriter is a small interface containing Header, WriteHeader, Write, Flush, and CanStream; when the underlying transport cannot stream output, CanStream must return false, in which case the server rejects GET (SSE listening) with 405 Method Not Allowed and keeps POST responses as buffered application/json rather than upgrading to text/event-stream. ServeHTTP remains unchanged and is still the regular net/http entry point.

Security and Browser Support Servers that require OAuth can declare authorization requirements via the RFC 9728 /.well-known/oauth-protected-resource endpoint referenced by the MCP authorization specification, automatically mounted using server.WithProtectedResourceMetadata (or server.WithSSEProtectedResourceMetadata), or integrated into a custom router with server.NewProtectedResourceMetadataHandler. Servers for browser-based MCP clients can enable cross-origin resource sharing on both HTTP transports; CORS is disabled by default and must be explicitly configured via server.WithStreamableHTTPCORS or server.WithSSECORS; the transport layer responds directly to preflight (OPTIONS) requests and adds the corresponding Access-Control-Allow-Origin, Access-Control-Allow-Credentials, Access-Control-Expose-Headers, and Vary headers to simple responses, using sensible defaults when options are omitted. Combining WithCORSAllowedOrigins("*") with WithCORSAllowCredentials() echoes the request Origin to remain specification-compliant. Both HTTP transports automatically protect local servers against DNS rebinding attacks: connections from loopback (127.0.0.1,[::1]) and requests whose Host header is not a localhost value are rejected with 403 Forbidden; this check is derived at runtime from the connection's local address, so it covers loopback connections regardless of whether the server listens on localhost or 0.0.0.0, and by default does not affect requests arriving from non-loopback addresses. A server bound to a non-loopback interface is not protected by this on that interface and can be protected by configuring a Host header allowlist; if a reverse proxy on the same host forwards via localhost and preserves the original Host header, you can use WithAllowedHosts to list the public hostnames, configure the proxy to rewrite Host to localhost, or explicitly disable all Host validation.

Usage and examples The basic flow is to create a server and register resources, tools, and prompts, then add options such as sessions, hooks, middleware, completion, CORS, and metadata as needed. The repository's examples/ directory provides examples, including examples/task_tool/ (demonstrating the TaskSupportRequired and TaskSupportOptional modes), examples/structured_input_and_output/ (struct-based type-safe input/output patterns), examples/typed_tools/ (type-safe tool handlers with strongly typed parameters), examples/custom_context/ (using a custom context in tool handlers), and more examples covering resources, prompts, and other content. Server hooks and request handlers are generated code and must be regenerated by running the generator; before running, Go must be installed and the goimports tool must be available. The generator automatically invokes goimports to format and fix imports.

Applicable scenarios and limitations Suitable for scenarios that require building an MCP server in Go and exposing internal data and operations to LLM applications in a standard way, for example wrapping database queries, file operations, external APIs, and system operations as tools, injecting knowledge or data into context as resources, and using prompts to codify interaction best practices; it is also suitable for production integrations that require session isolation, per-session tool customization, observability, and security hardening (OAuth metadata, CORS, DNS rebinding protection). In terms of limitations: both the project and the MCP specification are under active development, and some advanced capabilities are not yet complete; the materials do not provide specific installation commands, license, and costinformation, which is not yet provided; task concurrency has no upper limit by default and must be configured as needed; when binding to a non-loopback interface, DNS rebinding protection requires additionally configuring a Host allowlist.

Up/Down to navigate · Enter to open · ESC to closeBrowse all tools