Skip to content
Back to search

mcp-go

A Go implementation of the Model Context Protocol (MCP), enabling seamless integration between LLM applications and external data sources and tools.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/mark3labs/mcp-go with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/mark3labs/mcp-go'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/mark3labs--mcp-go/badge.svg)](/listings/mark3labs--mcp-go)

HTML

<a href="/listings/mark3labs--mcp-go"><img src="/api/listings/mark3labs--mcp-go/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

go get github.com/mark3labs/mcp-go

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 1,129 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. <!-- omit in toc -->
  2. <div align="center">
  3. <img src="./logo.png" alt="MCP Go Logo">
  4. [![Build](https://github.com/mark3labs/mcp-go/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/mark3labs/mcp-go/actions/workflows/ci.yml)
  5. [![Go Report Card](https://goreportcard.com/badge/github.com/mark3labs/mcp-go?cache)](https://goreportcard.com/report/github.com/mark3labs/mcp-go)
  6. [![GoDoc](https://pkg.go.dev/badge/github.com/mark3labs/mcp-go.svg)](https://pkg.go.dev/github.com/mark3labs/mcp-go)
  7. [![AgentRank](https://agentrank-ai.com/api/badge/tool/mark3labs--mcp-go)](https://agentrank-ai.com/tool/mark3labs--mcp-go/)
  8. <strong>A Go implementation of the Model Context Protocol (MCP), enabling seamless integration between LLM applications and external data sources and tools.</strong>
  9. <br>
  10. [![Tutorial](http://img.youtube.com/vi/qoaeYMrXJH0/0.jpg)](http://www.youtube.com/watch?v=qoaeYMrXJH0 "Tutorial")
  11. <br>
  12. Discuss the SDK on [Discord](https://discord.gg/RqSS2NQVsY)
  13. </div>
  14. ```go
  15. package main
  16. import (
  17. "context"
  18. "fmt"
  19. "os"
  20. "github.com/mark3labs/mcp-go/mcp"
  21. "github.com/mark3labs/mcp-go/server"
  22. )
  23. func main() {
  24. // Create a new MCP server
  25. s := server.NewMCPServer(
  26. "Demo 🚀",
  27. "1.0.0",
  28. server.WithToolCapabilities(false),
  29. )
  30. // Add tool
  31. tool := mcp.NewTool("hello_world",
  32. mcp.WithDescription("Say hello to someone"),
  33. mcp.WithString("name",
  34. mcp.Required(),
  35. mcp.Description("Name of the person to greet"),
  36. ),
  37. )
  38. // Add tool handler
  39. s.AddTool(tool, helloHandler)
  40. // Start the stdio server
  41. if err := server.ServeStdio(s); err != nil {
  42. fmt.Fprintf(os.Stderr, "Server error: %v\n", err)
  43. }
  44. }
  45. func helloHandler(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
  46. name, err := request.RequireString("name")
  47. if err != nil {
  48. return mcp.NewToolResultError(err.Error()), nil
  49. }
  50. return mcp.NewToolResultText(fmt.Sprintf("Hello, %s!", name)), nil
  51. }
  52. ```
  53. That's it!
  54. MCP Go handles all the complex protocol details and server management, so you can focus on building great tools. It aims to be high-level and easy to use.
  55. ### Key features:
  56. * **Fast**: High-level interface means less code and faster development
  57. * **Simple**: Build MCP servers with minimal boilerplate
  58. * **Complete***: MCP Go aims to provide a full implementation of the core MCP specification
  59. (\*emphasis on *aims*)
  60. 🚨 🚧 🏗️ *MCP Go is under active development, as is the MCP specification itself. Core features are working but some advanced capabilities are still in progress.*
  61. <!-- omit in toc -->
  62. ## Table of Contents
  63. - [Installation](#installation)
  64. - [Quickstart](#quickstart)
  65. - [What is MCP?](#what-is-mcp)
  66. - [Core Concepts](#core-concepts)
  67. - [Server](#server)
  68. - [Resources](#resources)
  69. - [Tools](#tools)
  70. - [Prompts](#prompts)
  71. - [Examples](#examples)
  72. - [Extras](#extras)
  73. - [Transports](#transports)
  74. - [OAuth Protected Resource Metadata](#oauth-protected-resource-metadata)
  75. - [Session Management](#session-management)
  76. - [Basic Session Handling](#basic-session-handling)
  77. - [Per-Session Tools](#per-session-tools)
  78. - [Tool Filtering](#tool-filtering)
  79. - [Working with Context](#working-with-context)
  80. - [Request Hooks](#request-hooks)
  81. - [Tool Handler Middleware](#tool-handler-middleware)
  82. - [Regenerating Server Code](#regenerating-server-code)
  83. ## Installation
  84. ```bash
  85. go get github.com/mark3labs/mcp-go
  86. ```
  87. ## Quickstart
  88. Let's create a simple MCP server that exposes a calculator tool and some data:
  89. ```go
  90. package main
  91. import (
  92. "context"
  93. "fmt"
  94. "os"
  95. "github.com/mark3labs/mcp-go/mcp"
  96. "github.com/mark3labs/mcp-go/server"
  97. )
  98. func main() {
  99. // Create a new MCP server
  100. s := server.NewMCPServer(
  101. "Calculator Demo",
  102. "1.0.0",
  103. server.WithToolCapabilities(false),
  104. server.WithRecovery(),
  105. )
  106. // Add a calculator tool
  107. calculatorTool := mcp.NewTool("calculate",
  108. mcp.WithDescription("Perform basic arithmetic operations"),
  109. mcp.WithString("operation",
  110. mcp.Required(),
  111. mcp.Description("The operation to perform (add, subtract, multiply, divide)"),
  112. mcp.Enum("add", "subtract", "multiply", "divide"),
  113. ),
  114. mcp.WithNumber("x",
  115. mcp.Required(),
  116. mcp.Description("First number"),
  117. ),
  118. mcp.WithNumber("y",
  119. mcp.Required(),
  120. mcp.Description("Second number"),
  121. ),
  122. )
  123. // Add the calculator handler
  124. s.AddTool(calculatorTool, func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
  125. // Using helper functions for type-safe argument access
  126. op, err := request.RequireString("operation")
  127. if err != nil {
  128. return mcp.NewToolResultError(err.Error()), nil
  129. }
  130. x, err := request.RequireFloat("x")
  131. if err != nil {
  132. return mcp.NewToolResultError(err.Error()), nil
  133. }
  134. y, err := request.RequireFloat("y")
  135. if err != nil {
  136. return mcp.NewToolResultError(err.Error()), nil
  137. }
  138. var result float64
  139. switch op {
  140. case "add":
  141. result = x + y
  142. case "subtract":
  143. result = x - y
  144. case "multiply":
  145. result = x * y
  146. case "divide":
  147. if y == 0 {
  148. return mcp.NewToolResultError("cannot divide by zero"), nil
  149. }
  150. result = x / y
  151. }
  152. return mcp.NewToolResultText(fmt.Sprintf("%.2f", result)), nil
  153. })
  154. // Start the server
  155. if err := server.ServeStdio(s); err != nil {
  156. fmt.Fprintf(os.Stderr, "Server error: %v\n", err)
  157. }
  158. }
  159. ```
  160. ## What is MCP?
  161. The [Model Context Protocol (MCP)](https://modelcontextprotocol.io) lets you build servers that expose data and functionality to LLM applications in a secure, standardized way. Think of it like a web API, but specifically designed for LLM interactions.
  162. MCP servers can:
  163. - Expose data through **Resources** (think of these sort of like GET endpoints; they are used to load information into the LLM's context)
  164. - Provide functionality through **Tools** (sort of like POST endpoints; they are used to execute code or otherwise produce a side effect)
  165. - Define interaction patterns through **Prompts** (reusable templates for LLM interactions)
  166. - And more!
  167. mcp-go implements the Model Context Protocol specification version 2025-11-25, with backward compatibility for versions 2025-06-18, 2025-03-26, and 2024-11-05.
  168. ## Core Concepts
  169. ### Server
  170. <details>
  171. <summary>Show Server Examples</summary>
  172. The server is your core interface to the MCP protocol. It handles connection management, protocol compliance, and message routing:
  173. ```go
  174. // Create a basic server
  175. s := server.NewMCPServer(
  176. "My Server", // Server name
  177. "1.0.0", // Version
  178. )
  179. // Start the server using stdio
  180. if err := server.ServeStdio(s); err != nil {
  181. log.Fatalf("Server error: %v", err)
  182. }
  183. ```
  184. </details>
  185. ### Resources
  186. <details>
  187. <summary>Show Resource Examples</summary>
  188. Resources are how you expose data to LLMs. They can be anything - files, API responses, database queries, system information, etc. Resources can be:
  189. - Static (fixed URI)
  190. - Dynamic (using URI templates)
  191. Here's a simple example of a static resource:
  192. ```go
  193. // Static resource example - exposing a README file
  194. resource := mcp.NewResource(
  195. "docs://readme",
  196. "Project README",
  197. mcp.WithResourceDescription("The project's README file"),
  198. mcp.WithMIMEType("text/markdown"),
  199. )
  200. // Add resource with its handler
  201. s.AddResource(resource, func(ctx context.Context, request mcp.ReadResourceRequest) ([]mcp.ResourceContents, error) {
  202. content, err := os.ReadFile("README.md")
  203. if err != nil {
  204. return nil, err
  205. }
  206. return []mcp.ResourceContents{
  207. mcp.TextResourceContents{
  208. URI: "docs://readme",
  209. MIMEType: "text/markdown",
  210. Text: string(content),
  211. },
  212. }, nil
  213. })
  214. ```
  215. And here's an example of a dynamic resource using a template:
  216. ```go
  217. // Dynamic resource example - user profiles by ID
  218. template := mcp.NewResourceTemplate(
  219. "users://{id}/profile",
  220. "User Profile",
  221. mcp.WithTemplateDescription("Returns user profile information"),
  222. mcp.WithTemplateMIMEType("application/json"),
  223. )
  224. // Add template with its handler
  225. s.AddResourceTemplate(template, func(ctx context.Context, request mcp.ReadResourceRequest) ([]mcp.ResourceContents, error) {
  226. // Extract ID from the URI using regex matching
  227. // The server automatically matches URIs to templates
  228. userID := extractIDFromURI(request.Params.URI)
  229. profile, err := getUserProfile(userID) // Your DB/API call here
  230. if err != nil {
  231. return nil, err
  232. }
  233. return []mcp.ResourceContents{
  234. mcp.TextResourceContents{
  235. URI: request.Params.URI,
  236. MIMEType: "application/json",
  237. Text: profile,
  238. },
  239. }, nil
  240. })
  241. ```
  242. The examples are simple but demonstrate the core concepts. Resources can be much more sophisticated - serving multiple contents, integrating with databases or external APIs, etc.
  243. </details>
  244. ### Tools
  245. <details>
  246. <summary>Show Tool Examples</summary>
  247. Tools let LLMs take actions through your server. Unlike resources, tools are expected to perform computation and have side effects. They're similar to POST endpoints in a REST API.
  248. #### Task-Augmented Tools
  249. Task-augmented tools execute asynchronously and return results via polling. This is useful for long-running operations that would otherwise block or time out. Task tools support three modes:
  250. - **TaskSupportForbidden** (default): The tool cannot be invoked as a task
  251. - **TaskSupportOptional**: The tool can be invoked as a task or synchronously
  252. - **TaskSupportRequired**: The tool must be invoked as a task
  253. ```go
  254. // Example: A tool that requires task execution
  255. processBatchTool := mcp.NewTool("process_batch",
  256. mcp.WithDescription("Process a batch of items asynchronously"),
  257. mcp.WithTaskSupport(mcp.TaskSupportRequired),
  258. mcp.WithArray("items",
  259. mcp.Description("Array of items to process"),
  260. mcp.WithStringItems(),
  261. mcp.Required(),
  262. ),
  263. )
  264. // Task tool handler returns CreateTaskResult instead of CallToolResult
  265. s.AddTaskTool(processBatchTool, func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CreateTaskResult, error) {
  266. items := request.GetStringSlice("items", []string{})
  267. // Long-running work here
  268. for i, item := range items {
  269. select {
  270. case <-ctx.Done():
  271. // Task was cancelled
  272. return nil, ctx.Err()
  273. default:
  274. // Process item...
  275. processItem(item)
  276. }
  277. }
  278. // Return result - task ID and metadata are managed by the server
  279. return &mcp.CreateTaskResult{
  280. Task: mcp.Task{
  281. // Task fields (ID, status, etc.) are populated by the server
  282. },
  283. }, nil
  284. })
  285. // Enable task capabilities when creating the server
  286. s := server.NewMCPServer(
  287. "Task Server",
  288. "1.0.0",
  289. server.WithTaskCapabilities(
  290. true, // listTasks: allows clients to list all tasks
  291. true, // cancel: allows clients to cancel running tasks
  292. true, // toolCallTasks: enables task augmentation for tools
  293. ),
  294. server.WithMaxConcurrentTasks(10), // Optional: limit concurrent running tasks
  295. )
  296. ```
  297. Task execution flow:
  298. 1. Client calls tool with task parameter
  299. 2. Server immediately returns task ID
  300. 3. Tool executes asynchronously in the background
  301. 4. Client polls `tasks/result` to retrieve the result
  302. 5. Server sends task status notifications on completion
  303. For optional task tools, the same tool can be called synchronously (without task parameter) or asynchronously (with task parameter):
  304. ```go
  305. // Tool with optional task support
  306. analyzeTool := mcp.NewTool("analyze_data",
  307. mcp.WithDescription("Analyze data - can run sync or async"),
  308. mcp.WithTaskSupport(mcp.TaskSupportOptional),
  309. mcp.WithString("data", mcp.Required()),
  310. )
  311. // Use AddTaskTool for hybrid tools that support both modes
  312. s.AddTaskTool(analyzeTool, func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CreateTaskResult, error) {
  313. // This handler runs when called as a task
  314. data := request.GetString("data", "")
  315. result := analyzeData(data)
  316. return &mcp.CreateTaskResult{
  317. Task: mcp.Task{},
  318. }, nil
  319. })
  320. // The server automatically handles both sync and async invocations
  321. // When called without task param: executes handler and returns immediately
  322. // When called with task param: executes handler asynchronously
  323. ```
  324. ##### Limiting Concurrent Tasks
  325. To prevent resource exhaustion, you can limit the number of concurrent running tasks:
  326. ```go
  327. s := server.NewMCPServer(
  328. "Task Server",
  329. "1.0.0",
  330. server.WithTaskCapabilities(true, true, true),
  331. server.WithMaxConcurrentTasks(10), // Allow up to 10 concurrent running tasks
  332. )
  333. ```
  334. When the limit is reached, new task creation requests will fail with an error. Completed, failed, or cancelled tasks don't count toward the limit - only tasks in "working" status. If `WithMaxConcurrentTasks` is not specified or set to 0, there is no limit on concurrent tasks.
  335. For traditional synchronous tools that execute and return results immediately:
  336. Simple calculation example:
  337. ```go
  338. calculatorTool := mcp.NewTool("calculate",
  339. mcp.WithDescription("Perform basic arithmetic calculations"),
  340. mcp.WithString("operation",
  341. mcp.Required(),
  342. mcp.Description("The arithmetic operation to perform"),
  343. mcp.Enum("add", "subtract", "multiply", "divide"),
  344. ),
  345. mcp.WithNumber("x",
  346. mcp.Required(),
  347. mcp.Description("First number"),
  348. ),
  349. mcp.WithNumber("y",
  350. mcp.Required(),
  351. mcp.Description("Second number"),
  352. ),
  353. )
  354. s.AddTool(calculatorTool, func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
  355. args := request.GetArguments()
  356. op := args["operation"].(string)
  357. x := args["x"].(float64)
  358. y := args["y"].(float64)
  359. var result float64
  360. switch op {
  361. case "add":
  362. result = x + y
  363. case "subtract":
  364. result = x - y
  365. case "multiply":
  366. result = x * y
  367. case "divide":
  368. if y == 0 {
  369. return mcp.NewToolResultError("cannot divide by zero"), nil
  370. }
  371. result = x / y
  372. }
  373. return mcp.FormatNumberResult(result), nil
  374. })
  375. ```
  376. HTTP request example:
  377. ```go
  378. httpTool := mcp.NewTool("http_request",
  379. mcp.WithDescription("Make HTTP requests to external APIs"),
  380. mcp.WithString("method",
  381. mcp.Required(),
  382. mcp.Description("HTTP method to use"),
  383. mcp.Enum("GET", "POST", "PUT", "DELETE"),
  384. ),
  385. mcp.WithString("url",
  386. mcp.Required(),
  387. mcp.Description("URL to send the request to"),
  388. mcp.Pattern("^https?://.*"),
  389. ),
  390. mcp.WithString("body",
  391. mcp.Description("Request body (for POST/PUT)"),
  392. ),
  393. )
  394. s.AddTool(httpTool, func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
  395. args := request.GetArguments()
  396. method := args["method"].(string)
  397. url := args["url"].(string)
  398. body := ""
  399. if b, ok := args["body"].(string); ok {
  400. body = b
  401. }
  402. // Create and send request
  403. var req *http.Request
  404. var err error
  405. if body != "" {
  406. req, err = http.NewRequest(method, url, strings.NewReader(body))
  407. } else {
  408. req, err = http.NewRequest(method, url, nil)
  409. }
  410. if err != nil {
  411. return mcp.NewToolResultErrorFromErr("unable to create request", err), nil
  412. }
  413. client := &http.Client{}
  414. resp, err := client.Do(req)
  415. if err != nil {
  416. return mcp.NewToolResultErrorFromErr("unable to execute request", err), nil
  417. }
  418. defer resp.Body.Close()
  419. // Return response
  420. respBody, err := io.ReadAll(resp.Body)
  421. if err != nil {
  422. return mcp.NewToolResultErrorFromErr("unable to read request response", err), nil
  423. }
  424. return mcp.NewToolResultText(fmt.Sprintf("Status: %d\nBody: %s", resp.StatusCode, string(respBody))), nil
  425. })
  426. ```
  427. Tools can be used for any kind of computation or side effect:
  428. - Database queries
  429. - File operations
  430. - External API calls
  431. - Calculations
  432. - System operations
  433. Each tool should:
  434. - Have a clear description
  435. - Validate inputs
  436. - Handle errors gracefully
  437. - Return structured responses
  438. - Use appropriate result types
  439. </details>
  440. ### Prompts
  441. <details>
  442. <summary>Show Prompt Examples</summary>
  443. Prompts are reusable templates that help LLMs interact with your server effectively. They're like "best practices" encoded into your server. Here are some examples:
  444. ```go
  445. // Simple greeting prompt
  446. s.AddPrompt(mcp.NewPrompt("greeting",
  447. mcp.WithPromptDescription("A friendly greeting prompt"),
  448. mcp.WithArgument("name",
  449. mcp.ArgumentDescription("Name of the person to greet"),
  450. ),
  451. ), func(ctx context.Context, request mcp.GetPromptRequest) (*mcp.GetPromptResult, error) {
  452. name := request.Params.Arguments["name"]
  453. if name == "" {
  454. name = "friend"
  455. }
  456. return mcp.NewGetPromptResult(
  457. "A friendly greeting",
  458. []mcp.PromptMessage{
  459. mcp.NewPromptMessage(
  460. mcp.RoleAssistant,
  461. mcp.NewTextContent(fmt.Sprintf("Hello, %s! How can I help you today?", name)),
  462. ),
  463. },
  464. ), nil
  465. })
  466. // Code review prompt with embedded resource
  467. s.AddPrompt(mcp.NewPrompt("code_review",
  468. mcp.WithPromptDescription("Code review assistance"),
  469. mcp.WithArgument("pr_number",
  470. mcp.ArgumentDescription("Pull request number to review"),
  471. mcp.RequiredArgument(),
  472. ),
  473. ), func(ctx context.Context, request mcp.GetPromptRequest) (*mcp.GetPromptResult, error) {
  474. prNumber := request.Params.Arguments["pr_number"]
  475. if prNumber == "" {
  476. return nil, fmt.Errorf("pr_number is required")
  477. }
  478. return mcp.NewGetPromptResult(
  479. "Code review assistance",
  480. []mcp.PromptMessage{
  481. mcp.NewPromptMessage(
  482. mcp.RoleUser,
  483. mcp.NewTextContent("Review the changes and provide constructive feedback."),
  484. ),
  485. mcp.NewPromptMessage(
  486. mcp.RoleAssistant,
  487. mcp.NewEmbeddedResource(mcp.ResourceContents{
  488. URI: fmt.Sprintf("git://pulls/%s/diff", prNumber),
  489. MIMEType: "text/x-diff",
  490. }),
  491. ),
  492. },
  493. ), nil
  494. })
  495. // Database query builder prompt
  496. s.AddPrompt(mcp.NewPrompt("query_builder",
  497. mcp.WithPromptDescription("SQL query builder assistance"),
  498. mcp.WithArgument("table",
  499. mcp.ArgumentDescription("Name of the table to query"),
  500. mcp.RequiredArgument(),
  501. ),
  502. ), func(ctx context.Context, request mcp.GetPromptRequest) (*mcp.GetPromptResult, error) {
  503. tableName := request.Params.Arguments["table"]
  504. if tableName == "" {
  505. return nil, fmt.Errorf("table name is required")
  506. }
  507. return mcp.NewGetPromptResult(
  508. "SQL query builder assistance",
  509. []mcp.PromptMessage{
  510. mcp.NewPromptMessage(
  511. mcp.RoleUser,
  512. mcp.NewTextContent("Help construct efficient and safe queries for the provided schema."),
  513. ),
  514. mcp.NewPromptMessage(
  515. mcp.RoleUser,
  516. mcp.NewEmbeddedResource(mcp.ResourceContents{
  517. URI: fmt.Sprintf("db://schema/%s", tableName),
  518. MIMEType: "application/json",
  519. }),
  520. ),
  521. },
  522. ), nil
  523. })
  524. ```
  525. Prompts can include:
  526. - System instructions
  527. - Required arguments
  528. - Embedded resources
  529. - Multiple messages
  530. - Different content types (text, images, etc.)
  531. - Custom URI schemes
  532. </details>
  533. ## Examples
  534. For examples, see the [`examples/`](examples/) directory.
  535. Key examples include:
  536. - [`examples/task_tool/`](examples/task_tool/) - Demonstrates task-augmented tools with TaskSupportRequired and TaskSupportOptional modes
  537. - [`examples/structured_input_and_output/`](examples/structured_input_and_output/) - Shows how to use struct-based input/output schemas with type-safe tool handlers
  538. - [`examples/typed_tools/`](examples/typed_tools/) - Demonstrates type-safe tool handlers with strongly-typed arguments
  539. - [`examples/custom_context/`](examples/custom_context/) - Shows how to use custom contexts in tool handlers
  540. - Additional examples covering resources, prompts, and more in the examples directory
  541. ## Extras
  542. ### Transports
  543. MCP-Go supports stdio, SSE and streamable-HTTP transport layers. For SSE transport, you can use `SetConnectionLostHandler()` to detect and handle disconnections for implementing reconnection logic.
  544. ### Embedding StreamableHTTP in non-net/http frameworks
  545. `StreamableHTTPServer` is an `http.Handler`, so it can be mounted in any
  546. router that speaks `net/http`. To embed it in a framework that does **not**
  547. go through `net/http` (e.g. [fasthttp](https://github.com/valyala/fasthttp)
  548. or [fiber](https://gofiber.io/)) without buffering the response through an
  549. adaptor, use the transport-agnostic `Handle` entry point:
  550. ```go
  551. func (s *StreamableHTTPServer) Handle(w HTTPResponseWriter, r *HTTPRequest)
  552. ```
  553. `HTTPRequest` is a plain struct (`Method`, `URL`, `Header`, `Body`,
  554. `Context`) and `HTTPResponseWriter` is a small interface (`Header`,
  555. `WriteHeader`, `Write`, `Flush`, `CanStream`). Implementations whose
  556. underlying transport cannot stream MUST return `false` from `CanStream`;
  557. the server will then reject GET (SSE listening) with `405 Method Not
  558. Allowed` and keep POST responses as buffered `application/json` instead of
  559. upgrading to `text/event-stream`.
  560. See the [HTTP transport docs](https://mcp-go.dev/transports/http#embedding-in-non-nethttp-frameworks)
  561. for a full fasthttp/fiber adapter example. `ServeHTTP` is unchanged and
  562. remains the conventional `net/http` entry point.
  563. ### OAuth Protected Resource Metadata
  564. Servers that require OAuth can advertise their authorization requirements
  565. via the [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728)
  566. `/.well-known/oauth-protected-resource` endpoint referenced by the
  567. [MCP authorization spec](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization).
  568. Use `server.WithProtectedResourceMetadata` (or
  569. `server.WithSSEProtectedResourceMetadata`) to auto-mount the endpoint, or
  570. `server.NewProtectedResourceMetadataHandler` to wire it into a custom router.
  571. See the [HTTP transport docs](https://mcp-go.dev/transports/http#oauth-protected-resource-metadata-rfc-9728) for examples.
  572. ```go
  573. httpServer := server.NewStreamableHTTPServer(mcpServer,
  574. server.WithProtectedResourceMetadata(server.ProtectedResourceMetadataConfig{
  575. Resource: "https://my-mcp-server.com",
  576. AuthorizationServers: []string{"https://auth.example.com"},
  577. ScopesSupported: []string{"mcp:read", "mcp:write"},
  578. }),
  579. )
  580. ```
  581. ### CORS for browser-based clients
  582. Servers exposed to browser-based MCP clients can opt into Cross-Origin
  583. Resource Sharing handling on either HTTP transport. CORS is disabled by
  584. default; configure it explicitly via `server.WithStreamableHTTPCORS` or
  585. `server.WithSSECORS`:
  586. ```go
  587. httpServer := server.NewStreamableHTTPServer(mcpServer,
  588. server.WithEndpointPath("/mcp"),
  589. server.WithStreamableHTTPCORS(
  590. server.WithCORSAllowedOrigins("https://my-ai-app.com", "http://localhost:3000"),
  591. server.WithCORSAllowCredentials(),
  592. server.WithCORSMaxAge(300),
  593. ),
  594. )
  595. ```
  596. The transport answers preflight (`OPTIONS`) requests directly and decorates
  597. simple responses with the appropriate `Access-Control-Allow-Origin`,
  598. `Access-Control-Allow-Credentials`, `Access-Control-Expose-Headers` and
  599. `Vary` headers. Sensible defaults are used when the corresponding option is
  600. omitted (`GET, POST, DELETE, OPTIONS` for methods; `Content-Type,
  601. Mcp-Session-Id, Mcp-Protocol-Version, Mcp-Method, Mcp-Name, Last-Event-ID,
  602. Authorization` for request headers;
  603. `Mcp-Session-Id` for exposed headers). Combining `WithCORSAllowedOrigins("*")`
  604. with `WithCORSAllowCredentials()` echoes the request `Origin` to remain
  605. spec-compliant.
  606. ### DNS rebinding protection
  607. Both HTTP transports automatically protect local servers against
  608. [DNS rebinding attacks](https://modelcontextprotocol.io/specification/2025-11-25/basic/security_best_practices#local-mcp-server-compromise):
  609. requests arriving over a loopback connection (`127.0.0.1`, `[::1]`) whose
  610. `Host` header is not a localhost value are rejected with `403 Forbidden`.
  611. The check is derived from the connection's local address at runtime, so it
  612. covers loopback connections whether the server listens on `localhost` or
  613. `0.0.0.0`, but by default it never affects requests arriving via
  614. non-loopback addresses.
  615. A server bound to a non-loopback interface (`:8080`, `0.0.0.0`, a LAN IP)
  616. is therefore not protected for requests arriving on that interface. To
  617. protect it, configure a `Host` header allowlist; any other non-localhost
  618. `Host` is then rejected regardless of the bind address:
  619. ```go
  620. httpServer := server.NewStreamableHTTPServer(mcpServer,
  621. // Or server.WithSSEAllowedHosts(...) on NewSSEServer.
  622. server.WithAllowedHosts("mcp.example.com"),
  623. )
  624. ```
  625. If a reverse proxy on the same host forwards requests via localhost while
  626. preserving the original `Host` header, list the public host name with
  627. `WithAllowedHosts`, configure the proxy to rewrite the `Host` header to
  628. localhost, or opt out of all `Host` validation explicitly:
  629. ```go
  630. httpServer := server.NewStreamableHTTPServer(mcpServer,
  631. // Or server.WithSSEDisableLocalhostProtection(true) on NewSSEServer.
  632. server.WithDisableLocalhostProtection(true),
  633. )
  634. ```
  635. See the [HTTP transport docs](https://mcp-go.dev/transports/http#dns-rebinding-protection)
  636. for details, including the caveat for the framework-agnostic `Handle` entry
  637. point.
  638. ### Session Management
  639. MCP-Go provides a robust session management system that allows you to:
  640. - Maintain separate state for each connected client
  641. - Register and track client sessions
  642. - Send notifications to specific clients
  643. - Provide per-session tool customization
  644. <details>
  645. <summary>Show Session Management Examples</summary>
  646. #### Basic Session Handling
  647. ```go
  648. // Create a server with session capabilities
  649. s := server.NewMCPServer(
  650. "Session Demo",
  651. "1.0.0",
  652. server.WithToolCapabilities(true),
  653. )
  654. // Implement your own ClientSession
  655. type MySession struct {
  656. id string
  657. notifChannel chan mcp.JSONRPCNotification
  658. isInitialized bool
  659. // Add custom fields for your application
  660. }
  661. // Implement the ClientSession interface
  662. func (s *MySession) SessionID() string {
  663. return s.id
  664. }
  665. func (s *MySession) NotificationChannel() chan<- mcp.JSONRPCNotification {
  666. return s.notifChannel
  667. }
  668. func (s *MySession) Initialize() {
  669. s.isInitialized = true
  670. }
  671. func (s *MySession) Initialized() bool {
  672. return s.isInitialized
  673. }
  674. // Register a session
  675. session := &MySession{
  676. id: "user-123",
  677. notifChannel: make(chan mcp.JSONRPCNotification, 10),
  678. }
  679. if err := s.RegisterSession(context.Background(), session); err != nil {
  680. log.Printf("Failed to register session: %v", err)
  681. }
  682. // Send notification to a specific client
  683. err := s.SendNotificationToSpecificClient(
  684. session.SessionID(),
  685. "notification/update",
  686. map[string]any{"message": "New data available!"},
  687. )
  688. if err != nil {
  689. log.Printf("Failed to send notification: %v", err)
  690. }
  691. // Unregister session when done
  692. s.UnregisterSession(context.Background(), session.SessionID())
  693. ```
  694. #### Per-Session Tools
  695. For more advanced use cases, you can implement the `SessionWithTools` interface to support per-session tool customization:
  696. ```go
  697. // Implement SessionWithTools interface for per-session tools
  698. type MyAdvancedSession struct {
  699. MySession // Embed the basic session
  700. sessionTools map[string]server.ServerTool
  701. }
  702. // Implement additional methods for SessionWithTools
  703. func (s *MyAdvancedSession) GetSessionTools() map[string]server.ServerTool {
  704. return s.sessionTools
  705. }
  706. func (s *MyAdvancedSession) SetSessionTools(tools map[string]server.ServerTool) {
  707. s.sessionTools = tools
  708. }
  709. // Create and register a session with tools support
  710. advSession := &MyAdvancedSession{
  711. MySession: MySession{
  712. id: "user-456",
  713. notifChannel: make(chan mcp.JSONRPCNotification, 10),
  714. },
  715. sessionTools: make(map[string]server.ServerTool),
  716. }
  717. if err := s.RegisterSession(context.Background(), advSession); err != nil {
  718. log.Printf("Failed to register session: %v", err)
  719. }
  720. // Add session-specific tools
  721. userSpecificTool := mcp.NewTool(
  722. "user_data",
  723. mcp.WithDescription("Access user-specific data"),
  724. )
  725. // You can use AddSessionTool (similar to AddTool)
  726. err := s.AddSessionTool(
  727. advSession.SessionID(),
  728. userSpecificTool,
  729. func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
  730. // This handler is only available to this specific session
  731. return mcp.NewToolResultText("User-specific data for " + advSession.SessionID()), nil
  732. },
  733. )
  734. if err != nil {
  735. log.Printf("Failed to add session tool: %v", err)
  736. }
  737. // Or use AddSessionTools directly with ServerTool
  738. /*
  739. err := s.AddSessionTools(
  740. advSession.SessionID(),
  741. server.ServerTool{
  742. Tool: userSpecificTool,
  743. Handler: func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
  744. // This handler is only available to this specific session
  745. return mcp.NewToolResultText("User-specific data for " + advSession.SessionID()), nil
  746. },
  747. },
  748. )
  749. if err != nil {
  750. log.Printf("Failed to add session tool: %v", err)
  751. }
  752. */
  753. // Delete session-specific tools when no longer needed
  754. err = s.DeleteSessionTools(advSession.SessionID(), "user_data")
  755. if err != nil {
  756. log.Printf("Failed to delete session tool: %v", err)
  757. }
  758. ```
  759. #### Tool Filtering
  760. You can also apply filters to control which tools are available to certain sessions:
  761. ```go
  762. // Add a tool filter that only shows tools with certain prefixes
  763. s := server.NewMCPServer(
  764. "Tool Filtering Demo",
  765. "1.0.0",
  766. server.WithToolCapabilities(true),
  767. server.WithToolFilter(func(ctx context.Context, tools []mcp.Tool) []mcp.Tool {
  768. // Get session from context
  769. session := server.ClientSessionFromContext(ctx)
  770. if session == nil {
  771. return tools // Return all tools if no session
  772. }
  773. // Example: filter tools based on session ID prefix
  774. if strings.HasPrefix(session.SessionID(), "admin-") {
  775. // Admin users get all tools
  776. return tools
  777. } else {
  778. // Regular users only get tools with "public-" prefix
  779. var filteredTools []mcp.Tool
  780. for _, tool := range tools {
  781. if strings.HasPrefix(tool.Name, "public-") {
  782. filteredTools = append(filteredTools, tool)
  783. }
  784. }
  785. return filteredTools
  786. }
  787. }),
  788. )
  789. ```
  790. #### Working with Context
  791. The session context is automatically passed to tool and resource handlers:
  792. ```go
  793. s.AddTool(mcp.NewTool("session_aware"), func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
  794. // Get the current session from context
  795. session := server.ClientSessionFromContext(ctx)
  796. if session == nil {
  797. return mcp.NewToolResultError("No active session"), nil
  798. }
  799. return mcp.NewToolResultText("Hello, session " + session.SessionID()), nil
  800. })
  801. // When using handlers in HTTP/SSE servers, you need to pass the context with the session
  802. httpHandler := func(w http.ResponseWriter, r *http.Request) {
  803. // Get session from somewhere (like a cookie or header)
  804. session := getSessionFromRequest(r)
  805. // Add session to context
  806. ctx := s.WithContext(r.Context(), session)
  807. // Use this context when handling requests
  808. // ...
  809. }
  810. ```
  811. </details>
  812. ### Request Hooks
  813. Hook into the request lifecycle by creating a `Hooks` object with your
  814. selection among the possible callbacks. This enables telemetry across all
  815. functionality, and observability of various facts, for example the ability
  816. to count improperly-formatted requests, or to log the agent identity during
  817. initialization.
  818. Add the `Hooks` to the server at the time of creation using the
  819. `server.WithHooks` option.
  820. ### Tool Handler Middleware
  821. Add middleware to tool call handlers using the `server.WithToolHandlerMiddleware` option. Middlewares can be registered on server creation and are applied on every tool call.
  822. A recovery middleware option is available to recover from panics in a tool call and can be added to the server with the `server.WithRecovery` option.
  823. ### Prompt Handler Middleware
  824. Add middleware to prompt handlers using the `server.WithPromptHandlerMiddleware` option. Middlewares can be registered on server creation and are applied on every `prompts/get` call.
  825. ### Prompt Filtering
  826. Filter prompts based on context using the `server.WithPromptFilter` option. This works the same way as tool filtering but applies to `prompts/list` results.
  827. ### Regenerating Server Code
  828. Server hooks and request handlers are generated. Regenerate them by running:
  829. ```bash
  830. go generate ./...
  831. ```
  832. You need `go` installed and the `goimports` tool available. The generator runs
  833. `goimports` automatically to format and fix imports.
  834. ### Auto-completions
  835. When users are filling in argument values for a specific prompt (identified by name) or resource template (identified by URI), servers can provide contextual suggestions.
  836. To enable completion support, use the `server.WithCompletions()` option when creating your server.
  837. #### Completion Providers
  838. You can provide completion logic for both prompt arguments and resource template arguments by implementing the respective interfaces and passing them to the server as options.
  839. <details>
  840. <summary>Show Completion Provider Examples</summary>
  841. ```go
  842. type MyPromptCompletionProvider struct{}
  843. func (p *MyPromptCompletionProvider) CompletePromptArgument(
  844. ctx context.Context,
  845. promptName string,
  846. argument mcp.CompleteArgument,
  847. context mcp.CompleteContext,
  848. ) (*mcp.Completion, error) {
  849. // Example: provide style suggestions for a "code_review" prompt
  850. if promptName == "code_review" && argument.Name == "style" {
  851. styles := []string{"formal", "casual", "technical", "creative"}
  852. var suggestions []string
  853. // Filter based on current input
  854. for _, style := range styles {
  855. if strings.HasPrefix(style, argument.Value) {
  856. suggestions = append(suggestions, style)
  857. }
  858. }
  859. return &mcp.Completion{
  860. Values: suggestions,
  861. }, nil
  862. }
  863. // Return empty suggestions for unhandled cases
  864. return &mcp.Completion{Values: []string{}}, nil
  865. }
  866. type MyResourceCompletionProvider struct{}
  867. func (p *MyResourceCompletionProvider) CompleteResourceArgument(
  868. ctx context.Context,
  869. uri string,
  870. argument mcp.CompleteArgument,
  871. context mcp.CompleteContext,
  872. ) (*mcp.Completion, error) {
  873. // Example: provide file path completions
  874. if uri == "file:///{path}" && argument.Name == "path" {
  875. // You can access previously completed arguments from context.Arguments
  876. // context.Arguments is a map[string]string of already-resolved arguments
  877. paths := getMatchingPaths(argument.Value) // Your custom logic
  878. return &mcp.Completion{
  879. Values: paths[:min(len(paths), 100)], // Max 100 items
  880. Total: len(paths), // Total available matches
  881. HasMore: len(paths) > 100, // More results available
  882. }, nil
  883. }
  884. return &mcp.Completion{Values: []string{}}, nil
  885. }
  886. // Register the provider
  887. mcpServer := server.NewMCPServer(
  888. "my-server",
  889. "1.0.0",
  890. server.WithCompletions(),
  891. server.WithPromptCompletionProvider(&MyPromptCompletionProvider{}),
  892. server.WithResourceCompletionProvider(&MyResourceCompletionProvider{}),
  893. )
  894. ```
  895. </details>
  896. #### Completion Context
  897. For prompts or resource templates with multiple arguments, the `CompleteContext` parameter provides access to previously completed arguments. This allows you to provide contextual suggestions based on earlier choices.
  898. <details>
  899. <summary>Show Completion Context Example</summary>
  900. ```go
  901. func (p *MyProvider) CompleteResourceArgument(
  902. ctx context.Context,
  903. uri string,
  904. argument mcp.CompleteArgument,
  905. context mcp.CompleteContext,
  906. ) (*mcp.Completion, error) {
  907. // Access previously completed arguments
  908. if previousValue, ok := context.Arguments["previous_arg"]; ok {
  909. // Provide suggestions based on previous_arg value
  910. return getSuggestionsFor(argument.Value, previousValue), nil
  911. }
  912. return &mcp.Completion{Values: []string{}}, nil
  913. }
  914. ```
  915. </details>
  916. #### Response Constraints
  917. When returning completion results:
  918. - Maximum 100 items per response
  919. - Use `Total` to indicate the total number of available matches
  920. - Use `HasMore` to signal if additional results exist beyond the returned values

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.