AIStoreHub Package Vault: MCP Quickstart Resources
Package Slug: mcp-quickstart-resources
Archetype: mcp_server
Upstream Repository: https://github.com/modelcontextprotocol/quickstart-resources
Workspace Files & Specifications (35 files)
- AGENTS.md (3832 bytes)
# AGENTS.md Guidance for anyone changing these examples, human or agent. The [README](./README.md) covers what is here and how to run it. ## What this repository is for These are the companion examples for two tutorials on modelcontextprotocol.io: [Build an MCP server](https://modelcontextprotocol.io/docs/develop/build-server) and [Build an MCP client](https://modelcontextprotocol.io/docs/develop/build-client). The tutorials quote this code, so readers meet it line by line. Every change should leave the code easier to read, not just more complete. ## Keep the examples minimal - Show the protocol, not production engineering. No retries, caching, config layers, logging frameworks or helper abstractions unless a tutorial teaches them. - Prefer the SDK's most direct, idiomatic API over a clever or general one. - Add a feature only when it shows something a reader needs to know about MCP. If it would only make the example more robust, leave it out. - Keep dependencies to the MCP SDK, the Anthropic SDK and what the language needs to make an HTTP call or read `.env`. ## Comments Explanations belong in the tutorial pages and the example READMEs, not in the source. Keep comments to a minimum: add one only where the code would otherwise look wrong or surprising, such as a workaround for an SDK limitation, and keep it to a line or two. ## Keep the five languages in sync The Python, TypeScript, Go, Rust and Ruby versions of each example should behave the same way. - A behavior change goes into all five in the same pull request. If one language can't follow, say why in the pull request and in that example's README. - Differences that follow a language's conventions are fine (for example, `get-alerts` in TypeScript, `get_alerts` elsewhere). Differences in behavior are not. - Update every affected README: each one documents its own example, and the root README describes what all of them share. ## Keep the tutorials in sync The tutorials live in [`modelcontextprotocol/modelcontextprotocol`](https://github.com/modelcontextprotocol/modelcontextprotocol), under `docs/docs/<protocol version>/develop/build-server.mdx` and `build-client.mdx`. When a change touches code a tutorial quotes or describes, open a matching pull request there and link the two. ## Checks and tests Run `make check` before opening a pull request. It runs the linters and formatters, rebuilds every example and runs the smoke tests. `make help` lists the per-language targets, such as `make lint-go`, for when you only have some toolchains installed. | Language | Checks | |------------|-------------------------------------------------| | Python | `ruff check`, `ruff format --check` | | TypeScript | `tsc --noEmit` | | Go | `gofmt -l`, `go vet` | | Rust | `cargo fmt --check`, `cargo clippy -D warnings` | | Ruby | `ruby -wc`, failing on warnings | `make fmt` fixes formatting for Python, Go and Rust. - A change to client behavior needs matching changes to the mock MCP server and the tool-loop test in [`tests/helpers`](./tests/helpers), so CI exercises the new behavior in all five clients. See [`tests/README.md`](./tests/README.md). - Tests never call a real Anthropic API. Server tests may reach the National Weather Service API, and treat it being unreachable as a skip. ## Dependencies Pin to released SDK versions, and commit the lockfiles. Dependabot opens the routine upgrades. When an SDK upgrade changes how an example has to be written, update all five languages and the tutorials as above. ## Pull requests Follow the Contributing section of the [README](./README.md#contributing). In particular, say in the pull request if AI assistance was used.
- aistorehub.json (556 bytes)
{ "name": "MCP Quickstart Resources", "slug": "mcp-quickstart-resources", "version": "1.0.0", "type": "mcp_server", "description": "Official templates, starter code, and architectural guidelines for building and packaging custom MCP servers in Python and TypeScript.", "owner": "community", "repository": "catalog", "github_repo_url": "https://github.com/modelcontextprotocol/quickstart-resources", "tags": [ "boilerplate", "mcp", "typescript", "quickstart", "python" ], "imported_at": "2026-11-22T00:08:35.478Z" } - INSTRUCTIONS.md (468 bytes)
# MCP Quickstart Resources (mcp-quickstart-resources) **System Type:** mcp_server **Maintainer:** @community ## System Purpose & Directives Official templates, starter code, and architectural guidelines for building and packaging custom MCP servers in Python and TypeScript. ## Operational Directives 1. Read and analyze the user query carefully. 2. Utilize workspace tools to produce rigorous, reproducible results. 3. Verify and test all output before delivery.
- LICENSE (12227 bytes)
The MCP project is undergoing a licensing transition from the MIT License to the Apache License, Version 2.0 ("Apache-2.0"). All new code and specification contributions to the project are licensed under Apache-2.0. Documentation contributions (excluding specifications) are licensed under CC-BY-4.0. Contributions for which relicensing consent has been obtained are licensed under Apache-2.0. Contributions made by authors who originally licensed their work under the MIT License and who have not yet granted explicit permission to relicense remain licensed under the MIT License. No rights beyond those granted by the applicable original license are conveyed for such contributions. --- Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to the Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS --- MIT License Copyright (c) 2024-2025 Model Context Protocol a Series of LF Projects, LLC. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --- Creative Commons Attribution 4.0 International (CC-BY-4.0) Documentation in this project (excluding specifications) is licensed under CC-BY-4.0. See https://creativecommons.org/licenses/by/4.0/legalcode for the full license text. - Makefile (3369 bytes)
# Lint, format, build and test every example. `make check` is what CI runs. # Each per-language target needs only that language's toolchain. PYTHON_DIRS := weather-server-python mcp-client-python TS_DIRS := weather-server-typescript mcp-client-typescript tests/helpers GO_DIRS := weather-server-go mcp-client-go RUST_DIRS := weather-server-rust mcp-client-rust RUBY_FILES := weather-server-ruby/weather.rb mcp-client-ruby/client.rb .PHONY: help check lint fmt build test \ lint-python lint-typescript lint-go lint-rust lint-ruby \ fmt-python fmt-go fmt-rust \ build-typescript build-go build-rust help: @echo "make check lint, then build and run the smoke tests" @echo "make lint check formatting and lint every example" @echo "make fmt format Python, Go and Rust in place" @echo "make build rebuild the TypeScript, Go and Rust examples" @echo "make test rebuild, then run tests/smoke-test.sh" @echo "Per language: lint-{python,typescript,go,rust,ruby}," @echo " fmt-{python,go,rust}, build-{typescript,go,rust}" # Lint first, then test, even under `make -j`: both install npm packages. check: lint $(MAKE) test lint: lint-python lint-typescript lint-go lint-rust lint-ruby fmt: fmt-python fmt-go fmt-rust build: build-typescript build-go build-rust # smoke-test.sh builds only what is missing, so rebuild first to avoid # testing stale binaries. test: build ./tests/smoke-test.sh lint-python: @set -e; for d in $(PYTHON_DIRS); do \ echo "== ruff $$d"; \ uv --directory $$d run --quiet ruff check .; \ uv --directory $$d run --quiet ruff format --check .; \ done fmt-python: @set -e; for d in $(PYTHON_DIRS); do \ uv --directory $$d run --quiet ruff check --fix .; \ uv --directory $$d run --quiet ruff format .; \ done lint-typescript: @set -e; for d in $(TS_DIRS); do \ echo "== tsc $$d"; \ [ -d $$d/node_modules ] || npm --prefix $$d ci --silent; \ (cd $$d && npx tsc --noEmit); \ done build-typescript: @set -e; for d in $(TS_DIRS); do \ [ -d $$d/node_modules ] || npm --prefix $$d ci --silent; \ npm --prefix $$d run --silent build; \ done lint-go: @set -e; for d in $(GO_DIRS); do \ echo "== gofmt, go vet $$d"; \ unformatted=$$(cd $$d && gofmt -l .); \ if [ -n "$$unformatted" ]; then echo "needs gofmt: $$unformatted"; exit 1; fi; \ (cd $$d && go vet ./...); \ done fmt-go: @set -e; for d in $(GO_DIRS); do (cd $$d && gofmt -w .); done # The binary names are the ones smoke-test.sh runs. `go build -o` adds no # `.exe` on Windows, so add it to replace the binary the smoke tests pick. build-go: cd weather-server-go && go build -o server$$(go env GOEXE) . cd mcp-client-go && go build -o mcp-client-go$$(go env GOEXE) . lint-rust: @set -e; for d in $(RUST_DIRS); do \ echo "== rustfmt, clippy $$d"; \ (cd $$d && cargo fmt --check && cargo clippy --quiet --all-targets -- -D warnings); \ done fmt-rust: @set -e; for d in $(RUST_DIRS); do (cd $$d && cargo fmt); done build-rust: @set -e; for d in $(RUST_DIRS); do (cd $$d && cargo build --quiet --release); done # `ruby -wc` exits 0 even when it prints warnings, so fail on the output. lint-ruby: @set -e; for f in $(RUBY_FILES); do \ echo "== ruby -wc $$f"; \ out=$$(ruby -wc $$f 2>&1) || { echo "$$out"; exit 1; }; \ echo "$$out"; \ if echo "$$out" | grep -q 'warning:'; then exit 1; fi; \ done - mcp-client-go/main.go (13176 bytes)
package main import ( "bufio" "context" "encoding/base64" "encoding/json" "fmt" "log" "os" "os/exec" "strings" "github.com/anthropics/anthropic-sdk-go/v2" "github.com/anthropics/anthropic-sdk-go/v2/option" "github.com/google/jsonschema-go/jsonschema" "github.com/joho/godotenv" "github.com/modelcontextprotocol/go-sdk/mcp" ) var model = anthropic.ModelClaudeSonnet5 // Sonnet 5 thinks adaptively unless told otherwise, and max_tokens caps thinking // plus the reply, so leave room for both. const maxTokens = 10000 const maxToolTurns = 10 const systemPrompt = "You are a helpful assistant. Use the available tools when they help answer the question." // Image types the Messages API accepts. var supportedImageTypes = map[string]bool{ "image/jpeg": true, "image/png": true, "image/gif": true, "image/webp": true, } // toolResultContent translates an MCP tool result into content for an // Anthropic tool_result. // // MCP and Anthropic content blocks differ, so each kind is converted. A kind // the model cannot take becomes a placeholder rather than vanishing, so the // model knows something was there. func toolResultContent(result *mcp.CallToolResult) []anthropic.ToolResultBlockParamContentUnion { var content []anthropic.ToolResultBlockParamContentUnion text := func(s string) { if s == "" { return } content = append(content, anthropic.ToolResultBlockParamContentUnion{OfText: &anthropic.TextBlockParam{Text: s}}) } hasText := false for _, block := range result.Content { switch b := block.(type) { case *mcp.TextContent: hasText = hasText || b.Text != "" text(b.Text) case *mcp.ImageContent: if !supportedImageTypes[b.MIMEType] { text("[unsupported result type: image]") continue } content = append(content, anthropic.ToolResultBlockParamContentUnion{OfImage: &anthropic.ImageBlockParam{ Source: anthropic.ImageBlockParamSourceUnion{OfBase64: &anthropic.Base64ImageSourceParam{ // The SDK holds the decoded bytes; the API wants base64. Data: base64.StdEncoding.EncodeToString(b.Data), MediaType: anthropic.Base64ImageSourceMediaType(b.MIMEType), }}, }}) case *mcp.EmbeddedResource: if b.Resource == nil || b.Resource.Blob != nil { text("[unsupported result type: resource]") continue } text(b.Resource.Text) default: text(fmt.Sprintf("[unsupported result type: %s]", contentType(block))) } } // A structured result SHOULD also carry serialized JSON in a text block, but // only SHOULD, so serialize it when no text came with it. if !hasText && result.StructuredContent != nil { if data, err := json.Marshal(result.StructuredContent); err == nil { text(string(data)) } } return content } // contentType returns an MCP content block's wire type, such as "audio". func contentType(block mcp.Content) string { var wire struct { Type string `json:"type"` } if data, err := block.MarshalJSON(); err == nil && json.Unmarshal(data, &wire) == nil && wire.Type != "" { return wire.Type } return "unknown" } type MCPClient struct { anthropic *anthropic.Client session *mcp.ClientSession tools []anthropic.ToolUnionParam messages []anthropic.MessageParam // Compiled outputSchema per tool name, for validating results. outputSchemas map[string]*jsonschema.Resolved } func NewMCPClient() (*MCPClient, error) { // .env is optional; the key may come from the environment instead. _ = godotenv.Load() client := anthropic.NewClient(option.WithAPIKey(os.Getenv("ANTHROPIC_API_KEY"))) return &MCPClient{ anthropic: &client, }, nil } func (c *MCPClient) ConnectToServer(ctx context.Context, serverArgs []string) error { if len(serverArgs) == 0 { return fmt.Errorf("no server command provided") } // Create command to spawn server process cmd := exec.CommandContext(ctx, serverArgs[0], serverArgs[1:]...) // Create MCP client client := mcp.NewClient( &mcp.Implementation{ Name: "mcp-client-go", Version: "1.0.0", }, nil, ) // Connect using CommandTransport transport := &mcp.CommandTransport{ Command: cmd, } session, err := client.Connect(ctx, transport, nil) if err != nil { return fmt.Errorf("failed to connect to server: %w", err) } c.session = session // The tools are listed once, here; this client doesn't follow later changes. toolsResult, err := session.ListTools(ctx, &mcp.ListToolsParams{}) if err != nil { return fmt.Errorf("failed to list tools: %w", err) } var toolNames []string // Convert MCP tools to Anthropic tool format c.outputSchemas = make(map[string]*jsonschema.Resolved) for _, tool := range toolsResult.Tools { toolNames = append(toolNames, tool.Name) anthropicTool, err := mcpToolToAnthropicTool(tool) if err != nil { return fmt.Errorf("failed to convert mcp tool to anthropic tool: %w", err) } c.tools = append(c.tools, anthropicTool) resolved, err := resolveOutputSchema(tool) if err != nil { return fmt.Errorf("failed to compile output schema of tool %s: %w", tool.Name, err) } if resolved != nil { c.outputSchemas[tool.Name] = resolved } } fmt.Printf("Connected to server with tools: %v\n", toolNames) return nil } func mcpToolToAnthropicTool(tool *mcp.Tool) (anthropic.ToolUnionParam, error) { var zeroTool anthropic.ToolUnionParam schemaJSON, err := json.Marshal(tool.InputSchema) if err != nil { return zeroTool, fmt.Errorf("failed to marshal input schema of mcp tool: %w", err) } var schema anthropic.ToolInputSchemaParam err = json.Unmarshal(schemaJSON, &schema) if err != nil { return zeroTool, fmt.Errorf("failed to unmarshal to anthropic input schema: %w", err) } toolParam := anthropic.ToolParam{ Name: tool.Name, Description: anthropic.String(tool.Description), InputSchema: schema, } return anthropic.ToolUnionParam{ OfTool: &toolParam, }, nil } // resolveOutputSchema compiles a tool's declared outputSchema, or returns // (nil, nil) when it declares none. OutputSchema is `any` because the root may // be any JSON Schema, so round-trip through JSON to accept every form. func resolveOutputSchema(tool *mcp.Tool) (*jsonschema.Resolved, error) { if tool.OutputSchema == nil { return nil, nil } raw, err := json.Marshal(tool.OutputSchema) if err != nil { return nil, fmt.Errorf("failed to marshal output schema: %w", err) } var schema jsonschema.Schema if err := json.Unmarshal(raw, &schema); err != nil { return nil, fmt.Errorf("failed to unmarshal output schema: %w", err) } return schema.Resolve(nil) } // validateToolOutput checks a result against its tool's declared outputSchema. // Error results are exempt: they carry a message, not data. func (c *MCPClient) validateToolOutput(name string, result *mcp.CallToolResult) error { resolved, ok := c.outputSchemas[name] if !ok || result.IsError { return nil } if result.StructuredContent == nil { return fmt.Errorf("tool %s declares an output schema but returned no structured content", name) } if err := resolved.Validate(result.StructuredContent); err != nil { return fmt.Errorf("structured content from tool %s does not match its output schema: %w", name, err) } return nil } func (c *MCPClient) ProcessQuery(ctx context.Context, query string) (string, error) { if c.session == nil { return "", fmt.Errorf("client is not connected to any server") } historyLength := len(c.messages) c.messages = append(c.messages, anthropic.NewUserMessage(anthropic.NewTextBlock(query))) var finalText []string for turn := 0; turn <= maxToolTurns; turn++ { // Tools are passed on every call so Claude can keep calling them. response, err := c.anthropic.Messages.New(ctx, anthropic.MessageNewParams{ Model: model, MaxTokens: maxTokens, System: []anthropic.TextBlockParam{{Text: systemPrompt}}, Messages: c.messages, Tools: c.tools, }) if err != nil { return "", fmt.Errorf("anthropic API request failed: %w", err) } if response.StopReason == anthropic.StopReasonRefusal { // Drop the refused query so a follow-up doesn't send it again. c.messages = c.messages[:historyLength] finalText = append(finalText, "[The model declined to answer; the query is not kept in history]") break } for _, block := range response.Content { if b, ok := block.AsAny().(anthropic.TextBlock); ok { finalText = append(finalText, b.Text) } } if response.StopReason == anthropic.StopReasonMaxTokens { finalText = append(finalText, "[Reply cut off at the max_tokens limit]") break } if response.StopReason != anthropic.StopReasonToolUse { // The API rejects an empty assistant message, so an empty reply isn't kept. if len(response.Content) > 0 { c.messages = append(c.messages, response.ToParam()) } break } if turn == maxToolTurns { finalText = append(finalText, fmt.Sprintf("[Stopped after %d tool-use turns]", maxToolTurns)) break } // Execute every tool call in this response and collect the results var anthropicToolResults []anthropic.ContentBlockParamUnion for _, block := range response.Content { toolUseBlock, ok := block.AsAny().(anthropic.ToolUseBlock) if !ok { continue } // Add information about the tool call to final text finalText = append(finalText, fmt.Sprintf("[Calling tool %s with args %s]", toolUseBlock.Name, string(toolUseBlock.Input))) // Call the MCP server tool mcpToolResult, err := c.session.CallTool(ctx, &mcp.CallToolParams{ Name: toolUseBlock.Name, Arguments: toolUseBlock.Input, }) if err != nil { // A rejected call is the model's mistake to correct, so it goes // back as a failed tool_result rather than ending the query. // Every tool_use still needs a matching result. finalText = append(finalText, fmt.Sprintf("[%s failed: %v]", toolUseBlock.Name, err)) anthropicToolResults = append(anthropicToolResults, anthropic.NewToolResultBlock( toolUseBlock.ID, fmt.Sprintf("Tool call %s failed: %v", toolUseBlock.Name, err), true, )) continue } if err := c.validateToolOutput(toolUseBlock.Name, mcpToolResult); err != nil { return "", err } // StructuredContent is data the application can use directly. if items, ok := mcpToolResult.StructuredContent.([]any); ok { finalText = append(finalText, fmt.Sprintf("[%s returned %d items]", toolUseBlock.Name, len(items))) } anthropicToolResults = append(anthropicToolResults, anthropic.ContentBlockParamUnion{ OfToolResult: &anthropic.ToolResultBlockParam{ ToolUseID: toolUseBlock.ID, Content: toolResultContent(mcpToolResult), IsError: anthropic.Bool(mcpToolResult.IsError), }, }) } // Every tool_use needs a matching tool_result, all in one user message. c.messages = append(c.messages, response.ToParam()) c.messages = append(c.messages, anthropic.NewUserMessage(anthropicToolResults...)) } return strings.Join(finalText, "\n"), nil } func (c *MCPClient) ChatLoop(ctx context.Context) error { fmt.Println("\nMCP Client Started!") fmt.Println("Type your queries, 'clear' to forget the conversation, or 'quit' to exit.") scanner := bufio.NewScanner(os.Stdin) for { fmt.Print("\nQuery: ") if !scanner.Scan() { break // EOF } query := strings.TrimSpace(scanner.Text()) if strings.EqualFold(query, "quit") { break } if strings.EqualFold(query, "clear") { c.messages = nil fmt.Println("\nConversation cleared.") continue } if query == "" { continue } historyLength := len(c.messages) response, err := c.ProcessQuery(ctx, query) if err != nil { // Drop the failed query so a follow-up doesn't send it again. c.messages = c.messages[:historyLength] fmt.Printf("\nError: %v\n", err) continue } fmt.Printf("\n%s\n", response) } return scanner.Err() } func (c *MCPClient) Cleanup() error { if c.session != nil { if err := c.session.Close(); err != nil { return fmt.Errorf("failed to close session: %w", err) } c.session = nil } return nil } func main() { if len(os.Args) < 2 { fmt.Fprintln(os.Stderr, "Usage: go run . <server_command> [args...]") os.Exit(1) } serverArgs := os.Args[1:] client, err := NewMCPClient() if err != nil { log.Fatalf("Failed to create MCP client: %v", err) } ctx := context.Background() if err := client.ConnectToServer(ctx, serverArgs); err != nil { log.Fatalf("Failed to connect to MCP server: %v", err) } // Connecting and listing tools needs no credentials; querying them does. // Matching the Python and TypeScript clients, report and exit rather than // failing, so the connection itself can be exercised without a key. if os.Getenv("ANTHROPIC_API_KEY") == "" { fmt.Println("\nNo ANTHROPIC_API_KEY found. To query these tools with Claude, set your API key:") fmt.Println(" export ANTHROPIC_API_KEY=your-api-key-here") if err := client.Cleanup(); err != nil { log.Printf("Cleanup error: %v", err) } return } if err := client.ChatLoop(ctx); err != nil { log.Printf("ChatLoop error: %v", err) } if err := client.Cleanup(); err != nil { log.Printf("Cleanup error: %v", err) } } - mcp-client-go/README.md (3211 bytes)
# An LLM-Powered Chatbot MCP Client written in Go An interactive chatbot MCP client: it launches an MCP server over stdio, lists its tools, and hands them to Claude, which can call them while answering your questions. This example accompanies the [Build an MCP client](https://modelcontextprotocol.io/docs/develop/build-client) tutorial. ## Prerequisites - Go 1.25+ - An [Anthropic API key](https://console.anthropic.com/) (optional — see below) ## Setup Put your API key in a `.env` file (or export `ANTHROPIC_API_KEY` in your shell — the `.env` file is optional): ```bash cp .env.example .env # then edit .env and add your key ``` ## Run the client Pass the command that starts the server — a binary or an interpreter plus its arguments: ```bash go run . ../weather-server-go/weather ``` (Build the server first with `go build -o weather` in its directory.) Any server command works, for example the Python server: ```bash go run . uv --directory ../weather-server-python run weather.py ``` Type a question (for example, "What's the weather in Sacramento?") and Claude answers using the server's tools. The client keeps the conversation for the whole session, so a follow-up such as "And the alerts for that state?" works. Type `clear` to start a new conversation, or `quit` (or press Ctrl-D) to exit and shut the server down cleanly. Ctrl-C stops the client at once. Without an `ANTHROPIC_API_KEY`, the client still connects, prints the server's tools, and exits — useful for verifying the MCP wiring without credentials. ## Structured content The SDK does not validate tool output, so this client compiles each declared `outputSchema` at connect time and checks results against it — the spec's client-side SHOULD. It uses [`jsonschema-go`](https://pkg.go.dev/github.com/google/jsonschema-go/jsonschema), already an SDK dependency. The two channels go to different readers: `Content` is forwarded to the model, while `StructuredContent` is used as data — the client counts the items it returns. See [Structured Content](https://modelcontextprotocol.io/specification/2026-07-28/server/tools#structured-content). Before a tool result goes to the model, the client converts it to the Messages API's block types. Text stays text, a PNG, JPEG, GIF or WebP image becomes an image block, and a text resource becomes its text. Anything else, such as audio, becomes a placeholder like `[unsupported result type: audio]`, so the model knows something was there. Empty text is dropped, because the Messages API rejects empty text blocks. A result with structured content and no text is sent as its JSON. A call the server rejects goes back to the model as a failed tool result, so it can correct itself, rather than ending the query. Every request sends the same short system prompt. When a reply stops early, the client says so: `[Reply cut off at the max_tokens limit]` when it ran out of tokens, and `[The model declined to answer; the query is not kept in history]` when the model refused. A reply that was cut off, refused, empty or stopped at the tool-turn limit is not added to the history, and a query that fails with an error is dropped from it, so the next request stays valid.
- mcp-client-python/client.py (9540 bytes)
import asyncio import json import os import signal import sys from contextlib import AsyncExitStack from anthropic import Anthropic from dotenv import load_dotenv from mcp import Client, MCPError, StdioServerParameters from mcp_types import CallToolResult, EmbeddedResource, ImageContent, Implementation, TextContent, TextResourceContents load_dotenv() # load environment variables from .env ANTHROPIC_MODEL = "claude-sonnet-5" # Sonnet 5 thinks adaptively unless told otherwise, and max_tokens caps thinking # plus the reply, so leave room for both. MAX_TOKENS = 10000 MAX_TOOL_TURNS = 10 SYSTEM_PROMPT = "You are a helpful assistant. Use the available tools when they help answer the question." # Image types the Messages API accepts. SUPPORTED_IMAGE_TYPES = {"image/jpeg", "image/png", "image/gif", "image/webp"} def tool_result_content(result: CallToolResult) -> list[dict]: """Translate an MCP tool result into content for an Anthropic tool_result. MCP and Anthropic content blocks differ, so each kind is converted. A kind the model cannot take becomes a placeholder rather than vanishing, so the model knows something was there. """ content: list[dict] = [] for block in result.content: if isinstance(block, TextContent): content.append({"type": "text", "text": block.text}) elif isinstance(block, ImageContent) and block.mime_type in SUPPORTED_IMAGE_TYPES: content.append( { "type": "image", "source": {"type": "base64", "media_type": block.mime_type, "data": block.data}, } ) elif isinstance(block, EmbeddedResource) and isinstance(block.resource, TextResourceContents): content.append({"type": "text", "text": block.resource.text}) else: content.append({"type": "text", "text": f"[unsupported result type: {block.type}]"}) content = [block for block in content if block.get("text") != ""] has_text = any(isinstance(block, TextContent) and block.text for block in result.content) if result.structured_content is not None and not has_text: content.append({"type": "text", "text": json.dumps(result.structured_content)}) return content class MCPClient: def __init__(self): # Initialize session and client objects self.client: Client | None = None self.exit_stack = AsyncExitStack() self._anthropic: Anthropic | None = None self.tools: list[dict] = [] self.messages: list[dict] = [] @property def anthropic(self) -> Anthropic: """Lazy-initialize Anthropic client when needed""" if self._anthropic is None: self._anthropic = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY")) return self._anthropic async def connect_to_server(self, server_command: list[str]): """Connect to an MCP server Args: server_command: The command that starts the server, and its arguments """ server_params = StdioServerParameters(command=server_command[0], args=server_command[1:]) # Client launches the command itself when given StdioServerParameters. # "auto", the SDK's default, probes server/discover, falling back to the # 2025-11-25 handshake. self.client = await self.exit_stack.enter_async_context( Client( server_params, mode="auto", client_info=Implementation(name="mcp-client-python", version="1.0.0"), ) ) # The tools are listed once, here; this client doesn't follow later changes. response = await self.client.list_tools() self.tools = [ {"name": tool.name, "description": tool.description, "input_schema": tool.input_schema} for tool in response.tools ] print( f"\nConnected over protocol {self.client.protocol_version} with tools:", [tool.name for tool in response.tools], ) async def process_query(self, query: str) -> str: """Process a query using Claude and available tools""" history_length = len(self.messages) self.messages.append({"role": "user", "content": query}) final_text = [] for turn in range(MAX_TOOL_TURNS + 1): response = self.anthropic.messages.create( model=ANTHROPIC_MODEL, max_tokens=MAX_TOKENS, system=SYSTEM_PROMPT, messages=self.messages, tools=self.tools, ) if response.stop_reason == "refusal": # Drop the refused query so a follow-up doesn't send it again. del self.messages[history_length:] final_text.append("[The model declined to answer; the query is not kept in history]") break final_text.extend(content.text for content in response.content if content.type == "text") if response.stop_reason == "max_tokens": final_text.append("[Reply cut off at the max_tokens limit]") break if response.stop_reason != "tool_use": # The API rejects an empty assistant message, so an empty reply isn't kept. if response.content: self.messages.append({"role": "assistant", "content": response.content}) break if turn == MAX_TOOL_TURNS: final_text.append(f"[Stopped after {MAX_TOOL_TURNS} tool-use turns]") break tool_results = [] for tool_use in (content for content in response.content if content.type == "tool_use"): final_text.append(f"[Calling tool {tool_use.name} with args {tool_use.input}]") try: # call_tool validates the result against the declared schema. result = await self.client.call_tool(tool_use.name, tool_use.input) except MCPError as error: # A rejected call is the model's mistake to correct, so it goes # back as a failed tool_result rather than ending the query. # Every tool_use still needs a matching result. final_text.append(f"[{tool_use.name} failed: {error}]") tool_results.append( { "type": "tool_result", "tool_use_id": tool_use.id, "content": f"Tool call {tool_use.name} failed: {error}", "is_error": True, } ) continue # structured_content is data the application can use directly. if isinstance(result.structured_content, list): final_text.append(f"[{tool_use.name} returned {len(result.structured_content)} items]") tool_results.append( { "type": "tool_result", "tool_use_id": tool_use.id, "content": tool_result_content(result), "is_error": bool(result.is_error), } ) self.messages.append({"role": "assistant", "content": response.content}) self.messages.append({"role": "user", "content": tool_results}) return "\n".join(final_text) async def chat_loop(self): """Run an interactive chat loop""" print("\nMCP Client Started!") print("Type your queries, 'clear' to forget the conversation, or 'quit' to exit.") while True: # input() blocks, so keep it off the event loop. try: query = (await asyncio.to_thread(input, "\nQuery: ")).strip() except EOFError: break if query.lower() == "quit": break if not query: continue if query.lower() == "clear": self.messages.clear() print("\nConversation cleared.") continue history_length = len(self.messages) try: response = await self.process_query(query) print("\n" + response) except Exception as e: # Drop the failed query so a follow-up doesn't send it again. del self.messages[history_length:] print(f"\nError: {str(e)}") async def cleanup(self): """Clean up resources""" await self.exit_stack.aclose() async def main(): if len(sys.argv) < 2: print("Usage: uv run client.py <server_command> [args...]", file=sys.stderr) sys.exit(1) client = MCPClient() try: await client.connect_to_server(sys.argv[1:]) # Check if we have a valid API key to continue api_key = os.getenv("ANTHROPIC_API_KEY") if not api_key: print("\nNo ANTHROPIC_API_KEY found. To query these tools with Claude, set your API key:") print(" export ANTHROPIC_API_KEY=your-api-key-here") return await client.chat_loop() finally: await client.cleanup() if __name__ == "__main__": # Ctrl-C exits at once; otherwise Python waits for the thread blocked in input(). signal.signal(signal.SIGINT, signal.SIG_DFL) asyncio.run(main()) - mcp-client-python/pyproject.toml (1154 bytes)
[project] name = "mcp-client" version = "0.1.0" description = "A simple MCP client" readme = "README.md" requires-python = ">=3.10" dependencies = [ "anthropic>=2.8.0", "mcp>=2.3.0", # client.py imports TextContent from mcp_types, which `mcp` pins exactly. "mcp-types>=2.2.0", "python-dotenv>=1.2.4", ] [dependency-groups] dev = [ "ruff>=0.17.5", ] [tool.ruff] line-length = 120 target-version = "py310" extend-exclude = ["README.md"] [tool.ruff.lint] select = [ "C4", # flake8-comprehensions "C90", # mccabe "E", # pycodestyle "F", # pyflakes "I", # isort "PERF", # Perflint "PL", # Pylint "UP", # pyupgrade ] ignore = ["PERF203", "PLC0415", "PLR0402"] mccabe.max-complexity = 24 # Default is 10 [tool.ruff.lint.pylint] allow-magic-value-types = ["bytes", "float", "int", "str"] max-args = 23 # Default is 5 max-branches = 23 # Default is 12 max-returns = 13 # Default is 6 max-statements = 102 # Default is 50 - mcp-client-python/README.md (3373 bytes)
# An LLM-Powered Chatbot MCP Client written in Python An interactive chatbot MCP client: it launches an MCP server over stdio, lists its tools, and hands them to Claude, which can call them while answering your questions. This example accompanies the [Build an MCP client](https://modelcontextprotocol.io/docs/develop/build-client) tutorial. ## Prerequisites - Python 3.10+ - [uv](https://docs.astral.sh/uv/) - An [Anthropic API key](https://console.anthropic.com/) (optional — see below) ## Setup Put your API key in a `.env` file (or export `ANTHROPIC_API_KEY` in your shell): ```bash cp .env.example .env # then edit .env and add your key ``` ## Run the client Pass the command that starts the server, and its arguments: ```bash uv run client.py uv --directory ../weather-server-python run weather.py ``` or, against the TypeScript server (build it first — see its README): ```bash uv run client.py node ../weather-server-typescript/build/index.js ``` Type a question (for example, "What's the weather in Sacramento?") and Claude answers using the server's tools. The client keeps the conversation for the whole session, so a follow-up such as "And the alerts for that state?" works. Type `clear` to start a new conversation, or `quit` (or press Ctrl-D) to exit and shut the server down cleanly. Ctrl-C stops the client at once. Without an `ANTHROPIC_API_KEY`, the client still connects, prints the server's tools, and exits — useful for verifying the MCP wiring without credentials. ## Structured content `call_tool` validates every result against the tool's declared output schema, so the spec's client-side SHOULD needs no code here. The two channels go to different readers: `content` is forwarded to the model, while `structured_content` is used as data — when a tool returns an array, the client counts its items rather than re-reading the prose. See [Structured Content](https://modelcontextprotocol.io/specification/2026-07-28/server/tools#structured-content). Before a tool result goes to the model, the client converts it to the Messages API's block types. Text stays text, a PNG, JPEG, GIF or WebP image becomes an image block, and a text resource becomes its text. Anything else, such as audio, becomes a placeholder like `[unsupported result type: audio]`, so the model knows something was there. Empty text is dropped, because the Messages API rejects empty text blocks. A result with structured content and no text is sent as its JSON. A call the server rejects goes back to the model as a failed tool result, so it can correct itself, rather than ending the query. Every request sends the same short system prompt. When a reply stops early, the client says so: `[Reply cut off at the max_tokens limit]` when it ran out of tokens, and `[The model declined to answer; the query is not kept in history]` when the model refused. A reply that was cut off, refused, empty or stopped at the tool-turn limit is not added to the history, and a query that fails with an error is dropped from it, so the next request stays valid. `Client(server_params, mode="auto")` launches the server from its `StdioServerParameters`, then probes `server/discover` and falls back to the `2025-11-25` handshake; `client.protocol_version` reports which era you got. See [Protocol versions](https://py.sdk.modelcontextprotocol.io/v2/protocol-versions/).
- mcp-client-ruby/client.rb (8548 bytes)
# frozen_string_literal: true require "anthropic" require "dotenv/load" require "json" require "mcp" class MCPClient ANTHROPIC_MODEL = "claude-sonnet-5" # Sonnet 5 thinks adaptively unless told otherwise, and max_tokens caps thinking # plus the reply, so leave room for both. MAX_TOKENS = 10000 MAX_TOOL_TURNS = 10 SYSTEM_PROMPT = "You are a helpful assistant. Use the available tools when they help answer the question." # Image types the Messages API accepts. SUPPORTED_IMAGE_TYPES = ["image/jpeg", "image/png", "image/gif", "image/webp"].freeze def initialize @mcp_client = nil @transport = nil @anthropic_client = nil @tools = [] @messages = [] end def connect_to_server(server_command) @transport = MCP::Client::Stdio.new(command: server_command.first, args: server_command.drop(1)) @mcp_client = MCP::Client.new(transport: @transport) @mcp_client.connect(client_info: { name: "mcp-client-ruby", version: "1.0.0" }) # The tools are listed once, here; this client doesn't follow later changes. @tools = @mcp_client.tools # The spec says clients SHOULD validate structured results against the # schema the tool declares. This SDK's client does not do it, so compile # each declared schema once here and check results as they arrive. @output_schemas = @tools.each_with_object({}) do |tool, schemas| schemas[tool.name] = MCP::Tool::OutputSchema.new(tool.output_schema) if tool.output_schema end tool_names = @tools.map(&:name) puts "\nConnected to server with tools: #{tool_names}" end def chat_loop puts <<~MESSAGE MCP Client Started! Type your queries, 'clear' to forget the conversation, or 'quit' to exit. MESSAGE loop do print "\nQuery: " $stdout.flush # a pipe is not line-buffered, so show the prompt before waiting line = $stdin.gets break if line.nil? query = line.chomp.strip break if query.downcase == "quit" next if query.empty? if query.downcase == "clear" @messages = [] puts "\nConversation cleared." next end history_length = @messages.length begin response = process_query(query) puts "\n#{response}" rescue => e # Drop the failed query so a follow-up doesn't send it again. @messages.slice!(history_length..) puts "\nError: #{e.message}" end end end def cleanup @transport&.close end private # Translate an MCP tool result into content for an Anthropic tool_result. # # MCP and Anthropic content blocks differ, so each kind is converted. A kind # the model cannot take becomes a placeholder rather than vanishing, so the # model knows something was there. def tool_result_content(result) blocks = Array(result["content"]) content = blocks.map do |block| if block["type"] == "text" { type: "text", text: block["text"] } elsif block["type"] == "image" && SUPPORTED_IMAGE_TYPES.include?(block["mimeType"]) { type: "image", source: { type: "base64", media_type: block["mimeType"], data: block["data"] } } elsif block["type"] == "resource" && block.dig("resource", "text") { type: "text", text: block.dig("resource", "text") } else { type: "text", text: "[unsupported result type: #{block["type"]}]" } end end content.reject! { |block| block[:text] == "" } structured = result["structuredContent"] has_text = blocks.any? { |block| block["type"] == "text" && !block["text"].to_s.empty? } if !structured.nil? && !has_text content << { type: "text", text: structured.to_json } end content end def process_query(query) history_length = @messages.length @messages << { role: "user", content: query } available_tools = @tools.map do |tool| { name: tool.name, description: tool.description, input_schema: tool.input_schema } end final_text = [] (0..MAX_TOOL_TURNS).each do |turn| # Tools are passed on every call so Claude can keep calling them. response = anthropic_client.messages.create( model: ANTHROPIC_MODEL, max_tokens: MAX_TOKENS, system: SYSTEM_PROMPT, messages: @messages, tools: available_tools ) if response.stop_reason == :refusal # Drop the refused query so a follow-up doesn't send it again. @messages.slice!(history_length..) final_text << "[The model declined to answer; the query is not kept in history]" break end response.content.grep(Anthropic::Models::TextBlock) { |block| final_text << block.text } if response.stop_reason == :max_tokens final_text << "[Reply cut off at the max_tokens limit]" break end if response.stop_reason != :tool_use # The API rejects an empty assistant message, so an empty reply isn't kept. @messages << { role: "assistant", content: assistant_content(response) } unless response.content.empty? break end if turn == MAX_TOOL_TURNS final_text << "[Stopped after #{MAX_TOOL_TURNS} tool-use turns]" break end # Execute every tool call in this response and collect the results. tool_uses = response.content.grep(Anthropic::Models::ToolUseBlock) tool_results = tool_uses.map do |tool_use| final_text << "[Calling tool #{tool_use.name} with args #{tool_use.input.to_json}]" begin result = @mcp_client.call_tool(name: tool_use.name, arguments: tool_use.input) rescue MCP::Client::ServerError => e # A rejected call is the model's mistake to correct, so it goes back as # a failed tool_result rather than ending the query. Every tool_use # still needs a matching result. final_text << "[#{tool_use.name} failed: #{e.message}]" next { type: "tool_result", tool_use_id: tool_use.id, content: "Tool call #{tool_use.name} failed: #{e.message}", is_error: true } end # structured_content is data the application can use directly; when a # tool returns an array, count its items rather than re-reading prose. is_error = result.dig("result", "isError") == true structured = result.dig("result", "structuredContent") unless is_error @output_schemas[tool_use.name]&.validate_result(structured) final_text << "[#{tool_use.name} returned #{structured.length} items]" if structured.is_a?(Array) end { type: "tool_result", tool_use_id: tool_use.id, content: tool_result_content(result["result"]), is_error: is_error } end # Every tool_use needs a matching tool_result, all in one user message. @messages << { role: "assistant", content: assistant_content(response) } @messages << { role: "user", content: tool_results } end final_text.join("\n") end # Convert a response's content blocks back into request parameters. Thinking # blocks must go back unchanged, signature included, or the API rejects the # follow-up request. def assistant_content(response) response.content.filter_map do |block| case block when Anthropic::Models::TextBlock { type: "text", text: block.text } when Anthropic::Models::ToolUseBlock { type: "tool_use", id: block.id, name: block.name, input: block.input } when Anthropic::Models::ThinkingBlock { type: "thinking", thinking: block.thinking, signature: block.signature } when Anthropic::Models::RedactedThinkingBlock { type: "redacted_thinking", data: block.data } end end end def anthropic_client @anthropic_client ||= Anthropic::Client.new(api_key: ENV["ANTHROPIC_API_KEY"]) end end if ARGV.empty? warn "Usage: bundle exec ruby client.rb <server_command> [args...]" exit 1 end client = MCPClient.new begin client.connect_to_server(ARGV) api_key = ENV["ANTHROPIC_API_KEY"] if api_key.nil? || api_key.empty? puts <<~MESSAGE No ANTHROPIC_API_KEY found. To query these tools with Claude, set your API key: export ANTHROPIC_API_KEY=your-api-key-here MESSAGE exit end client.chat_loop rescue Interrupt # Ctrl-C: stop without a backtrace; `ensure` still cleans up. puts exit 130 rescue => e warn "Error: #{e.message}" exit 1 ensure client.cleanup end - mcp-client-ruby/README.md (3274 bytes)
# An LLM-Powered Chatbot MCP Client written in Ruby An interactive chatbot MCP client: it launches an MCP server over stdio, lists its tools, and hands them to Claude, which can call them while answering your questions. This example accompanies the [Build an MCP client](https://modelcontextprotocol.io/docs/develop/build-client) tutorial. ## Prerequisites - Ruby 3.4+ - Bundler - An [Anthropic API key](https://console.anthropic.com/) (optional — see below) ## Setup Install the gems, then put your API key in a `.env` file (or export `ANTHROPIC_API_KEY` in your shell): ```bash bundle install cp .env.example .env # then edit .env and add your key ``` ## Run the client Pass the command that starts the server, and its arguments: ```bash bundle exec ruby client.rb ruby ../weather-server-ruby/weather.rb ``` Type a question (for example, "What's the weather in Sacramento?") and Claude answers using the server's tools. The client keeps the conversation for the whole session, so a follow-up such as "And the alerts for that state?" works. Type `clear` to start a new conversation, or `quit` (or press Ctrl-D) to exit and shut the server down cleanly. Ctrl-C stops the client at once. Without an `ANTHROPIC_API_KEY`, the client still connects, prints the server's tools, and exits — useful for verifying the MCP wiring without credentials. ## Structured content The spec says clients SHOULD validate structured results against the schema the tool declares, and this SDK's client does not do it for you — `MCP::Client::Tool#output_schema` hands back the raw schema from the wire and nothing checks results against it. So the client compiles each declared schema once at connect time with `MCP::Tool::OutputSchema.new` and validates every non-error result. The two channels go to different readers: `content` is forwarded to the model, while `structured_content` is used as data — when a tool returns an array, the client counts its items rather than re-reading the prose. See [Structured Content](https://modelcontextprotocol.io/specification/2026-07-28/server/tools#structured-content). Before a tool result goes to the model, the client converts it to the Messages API's block types. Text stays text, a PNG, JPEG, GIF or WebP image becomes an image block, and a text resource becomes its text. Anything else, such as audio, becomes a placeholder like `[unsupported result type: audio]`, so the model knows something was there. Empty text is dropped, because the Messages API rejects empty text blocks. A result with structured content and no text is sent as its JSON. A call the server rejects goes back to the model as a failed tool result, so it can correct itself, rather than ending the query. Every request sends the same short system prompt. When a reply stops early, the client says so: `[Reply cut off at the max_tokens limit]` when it ran out of tokens, and `[The model declined to answer; the query is not kept in history]` when the model refused. A reply that was cut off, refused, empty or stopped at the tool-turn limit is not added to the history, and a query that fails with an error is dropped from it, so the next request stays valid. `MCP::Client::Stdio` offers `2026-07-28` by default, so no negotiation setup is needed here.
- mcp-client-rust/Cargo.toml (742 bytes)
[package] name = "mcp-client-rust" version = "0.1.0" edition = "2024" [dependencies] anyhow = "1.0.104" jsonschema = "0.61" # Only the client half of rmcp is needed, over a child-process stdio transport. rmcp = { version = "3.4", features = [ "client", "transport-io", "transport-child-process", ], default-features = false } # There is no official Anthropic SDK for Rust, so the Messages API is called # directly. That also keeps the provider's content blocks verbatim, which # matters for signed thinking blocks; see request_model. reqwest = { version = "0.13", features = ["json"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0.151" tokio = { version = "1.53", features = ["full"] } dotenvy = "0.15.7" - mcp-client-rust/README.md (4136 bytes)
# An LLM-Powered Chatbot MCP Client written in Rust An interactive chatbot MCP client: it launches an MCP server over stdio, lists its tools, and hands them to Claude, which can call them while answering your questions. This example accompanies the [Build an MCP client](https://modelcontextprotocol.io/docs/develop/build-client) tutorial. ## Prerequisites - Rust 1.88+ and Cargo - An [Anthropic API key](https://console.anthropic.com/) (optional — see below) ## Setup Export your API key, or put it in a `.env` file in this directory (the `.env` file is optional): ```bash export ANTHROPIC_API_KEY=your-api-key-here ``` ## Run the client Pass the command that starts the server — a binary or a script — after `--`: ```bash cargo run -- ../weather-server-rust/target/release/weather ``` (Build the server first with `cargo build --release` in its directory.) Type a question (for example, "What's the weather in Sacramento?") and Claude answers using the server's tools. The client keeps the conversation for the whole session, so a follow-up such as "And the alerts for that state?" works. Type `clear` to start a new conversation, or `quit` (or press Ctrl-D) to exit and shut the server down cleanly. Ctrl-C stops the client at once. Without an `ANTHROPIC_API_KEY`, the client still connects, prints the server's tools, and exits — useful for verifying the MCP wiring without credentials. ## Talking to Claude There is no official Anthropic SDK for Rust, so this client calls the [Messages API](https://docs.anthropic.com/en/api/messages) over HTTP with `reqwest`. That keeps the request shape visible, and it means an assistant turn can be fed back exactly as it arrived. Claude requires that: the blocks it sends must return unchanged on the next request, a thinking block's `signature` included, and a wrapper type that models only text and tool calls would drop the rest. `ANTHROPIC_BASE_URL` overrides the endpoint, as it does in the official SDKs for the other languages. ## Protocol negotiation rmcp's `serve` only performs the legacy `2025-11-25` `initialize` handshake, so this client uses `serve_with_lifecycle` with `ClientLifecycleMode::Auto` instead: one `server/discover` probe for `2026-07-28`, falling back to `initialize`. Matching the Python and TypeScript clients' `auto` mode, it also makes this era's features reachable — an array-rooted `outputSchema`, for one, which `get_alerts` uses. The negotiated revision is printed on connect. ## Structured content rmcp does not validate tool output, so this client compiles each declared `outputSchema` at connect time and checks results against it — the spec's client-side SHOULD. It uses the [`jsonschema`](https://docs.rs/jsonschema) crate, which rmcp's own documentation recommends. The two channels go to different readers: `content` is forwarded to the model, while `structured_content` is used as data — the client counts the items it returns. See [Structured Content](https://modelcontextprotocol.io/specification/2026-07-28/server/tools#structured-content). Before a tool result goes to the model, the client converts it to the Messages API's block types. Text stays text, a PNG, JPEG, GIF or WebP image becomes an image block, and a text resource becomes its text. Anything else, such as audio, becomes a placeholder like `[unsupported result type: audio]`, so the model knows something was there. Empty text is dropped, because the Messages API rejects empty text blocks. A result with structured content and no text is sent as its JSON. A call the server rejects goes back to the model as a failed tool result, so it can correct itself, rather than ending the query. Every request sends the same short system prompt. When a reply stops early, the client says so: `[Reply cut off at the max_tokens limit]` when it ran out of tokens, and `[The model declined to answer; the query is not kept in history]` when the model refused. A reply that was cut off, refused, empty or stopped at the tool-turn limit is not added to the history, and a query that fails with an error is dropped from it, so the next request stays valid.
- mcp-client-rust/src/main.rs (18677 bytes)
use anyhow::{Context, Result, bail}; use jsonschema::Validator; use rmcp::model::{ CallToolRequestParams, CallToolResult, ClientCapabilities, ClientConfig, ContentBlock, Implementation, ProtocolVersion, ResourceContents, Tool as McpTool, }; use rmcp::service::{ClientLifecycleMode, ClientServiceExt, RoleClient, RunningService}; use rmcp::transport::TokioChildProcess; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use std::collections::HashMap; use std::time::Duration; use tokio::io::{self, AsyncBufReadExt, BufReader}; use tokio::process::Command; const MODEL_ANTHROPIC: &str = "claude-sonnet-5"; /// Sonnet 5 thinks adaptively unless told otherwise, and max_tokens caps thinking /// plus the reply, so leave room for both. const MAX_TOKENS: u32 = 10000; const MAX_TOOL_TURNS: usize = 10; const SYSTEM_PROMPT: &str = "You are a helpful assistant. Use the available tools when they help answer the question."; const ANTHROPIC_API_BASE: &str = "https://api.anthropic.com"; const ANTHROPIC_VERSION: &str = "2026-10-21"; const REQUEST_TIMEOUT: Duration = Duration::from_secs(120); /// Image types the Messages API accepts. const SUPPORTED_IMAGE_TYPES: [&str; 4] = ["image/jpeg", "image/png", "image/gif", "image/webp"]; /// Translate an MCP tool result into content for an Anthropic tool_result. /// /// MCP and Anthropic content blocks differ, so each kind is converted. A kind /// the model cannot take becomes a placeholder rather than vanishing, so the /// model knows something was there. fn tool_result_content(result: &CallToolResult) -> Vec<Value> { let mut content: Vec<Value> = result .content .iter() .map(|block| match block { ContentBlock::Text(text) => json!({"type": "text", "text": text.text}), ContentBlock::Image(image) if SUPPORTED_IMAGE_TYPES.contains(&image.mime_type.as_str()) => { json!({ "type": "image", "source": {"type": "base64", "media_type": image.mime_type, "data": image.data}, }) } ContentBlock::Resource(resource) => match &resource.resource { ResourceContents::TextResourceContents { text, .. } => { json!({"type": "text", "text": text}) } _ => unsupported("resource"), }, other => { let kind = serde_json::to_value(other) .ok() .and_then(|value| value.get("type")?.as_str().map(str::to_string)) .unwrap_or_else(|| "unknown".to_string()); unsupported(&kind) } }) .collect(); content.retain(|block| block["text"] != ""); let has_text = result .content .iter() .any(|block| matches!(block, ContentBlock::Text(text) if !text.text.is_empty())); if !has_text && let Some(structured) = &result.structured_content { content.push(json!({"type": "text", "text": structured.to_string()})); } content } fn unsupported(kind: &str) -> Value { json!({"type": "text", "text": format!("[unsupported result type: {kind}]")}) } /// One turn of the conversation, as the Messages API takes it. /// /// `content` is a list of raw blocks rather than typed ones on purpose. An /// assistant turn is fed straight back on the next request, and Claude requires /// the blocks it sent to return unchanged -- a thinking block's `signature` /// included. Reserialising through a narrower type would drop whatever it does /// not model. #[derive(Serialize, Clone)] struct Message { role: &'static str, content: Vec<Value>, } impl Message { fn user(content: Vec<Value>) -> Self { Message { role: "user", content, } } fn assistant(content: Vec<Value>) -> Self { Message { role: "assistant", content, } } } /// A tool as the Messages API declares it, converted from an MCP tool. #[derive(Serialize, Clone)] struct ToolDefinition { name: String, #[serde(skip_serializing_if = "Option::is_none")] description: Option<String>, input_schema: Value, } #[derive(Serialize)] struct MessagesRequest<'a> { model: &'a str, max_tokens: u32, system: &'a str, messages: &'a [Message], tools: &'a [ToolDefinition], } #[derive(Deserialize)] struct MessagesResponse { content: Vec<Value>, stop_reason: Option<String>, } /// The `type` of a content block, when it has one. fn block_type(block: &Value) -> &str { block .get("type") .and_then(Value::as_str) .unwrap_or_default() } struct MCPClient { http: reqwest::Client, session: Option<RunningService<RoleClient, ClientConfig>>, tools: Vec<ToolDefinition>, messages: Vec<Message>, /// Compiled `outputSchema` per tool name. rmcp does not validate results, /// so this client does it with the `jsonschema` crate. output_schemas: HashMap<String, Validator>, } impl MCPClient { fn new() -> Result<Self> { Ok(MCPClient { http: reqwest::Client::builder() .timeout(REQUEST_TIMEOUT) .build() .context("Failed to build HTTP client")?, session: None, tools: Vec::new(), messages: Vec::new(), output_schemas: HashMap::new(), }) } /// Check a result against its tool's declared `outputSchema`. Error results /// are exempt: they carry a message, not data. fn validate_tool_output(&self, name: &str, result: &CallToolResult) -> Result<()> { let Some(validator) = self.output_schemas.get(name) else { return Ok(()); }; if result.is_error.unwrap_or(false) { return Ok(()); } let Some(structured) = &result.structured_content else { bail!("Tool {name} declares an output schema but returned no structured content"); }; if let Err(error) = validator.validate(structured) { bail!("Structured content from tool {name} does not match its output schema: {error}"); } Ok(()) } async fn connect_to_server(&mut self, server_args: &[String]) -> Result<()> { if self.session.is_some() { bail!("Client is already connected to a server"); } let mut command = Command::new(&server_args[0]); command.args(&server_args[1..]); let process = TokioChildProcess::new(command) .with_context(|| format!("Failed to spawn server process for {:?}", server_args))?; // Without a ClientConfig the client would report rmcp's own crate name // and version rather than its own. let config = ClientConfig::new( ClientCapabilities::default(), Implementation::new("mcp-client-rust", "1.0.0"), ); // `Auto` probes server/discover and falls back to the 2025-11-25 // initialize handshake, matching the Python and TypeScript clients. // `serve` alone would only ever do the legacy handshake, under which a // server cannot offer this era's features -- an array-rooted // `outputSchema`, for one, which get_alerts uses. let session = config .serve_with_lifecycle( process, ClientLifecycleMode::Auto { preferred_versions: vec![ProtocolVersion::V_2026_07_28], legacy_version: Some(ProtocolVersion::V_2025_11_25), }, ) .await?; // The tools are listed once, here; this client doesn't follow later changes. let rmcp_tools = session .list_all_tools() .await .context("Unable to list tools from server")?; let tool_names: Vec<String> = rmcp_tools .iter() .map(|tool| tool.name.to_string()) .collect(); let protocol_version = session .peer_info() .map(|info| info.protocol_version.to_string()) .unwrap_or_else(|| "unknown".to_string()); println!("Connected over protocol {protocol_version} with tools: {tool_names:?}"); // An outputSchema root may be any JSON Schema, not just an object. for tool in &rmcp_tools { let Some(schema) = &tool.output_schema else { continue; }; let schema = Value::Object(schema.as_ref().clone()); let validator = Validator::new(&schema).with_context(|| { format!("Failed to compile output schema of tool {}", tool.name) })?; self.output_schemas.insert(tool.name.to_string(), validator); } self.tools = convert_tools(&rmcp_tools); self.session = Some(session); Ok(()) } async fn process_query(&mut self, query: &str) -> Result<String> { let session = self .session .as_ref() .context("Client is not connected to any server")?; let history_length = self.messages.len(); self.messages .push(Message::user(vec![json!({"type": "text", "text": query})])); let mut final_text = Vec::new(); for turn in 0..=MAX_TOOL_TURNS { let response = self.request_model(&self.messages).await?; let stop_reason = response.stop_reason.as_deref().unwrap_or_default(); if stop_reason == "refusal" { // Drop the refused query so a follow-up doesn't send it again. self.messages.truncate(history_length); final_text.push( "[The model declined to answer; the query is not kept in history]".to_string(), ); break; } for block in &response.content { if block_type(block) == "text" && let Some(text) = block.get("text").and_then(Value::as_str) { final_text.push(text.to_string()); } } if stop_reason == "max_tokens" { final_text.push("[Reply cut off at the max_tokens limit]".to_string()); break; } if stop_reason != "tool_use" { // The API rejects an empty assistant message, so an empty reply isn't kept. if !response.content.is_empty() { self.messages.push(Message::assistant(response.content)); } break; } if turn == MAX_TOOL_TURNS { final_text.push(format!("[Stopped after {MAX_TOOL_TURNS} tool-use turns]")); break; } // Execute every tool call in this response and collect the results let mut tool_results = Vec::new(); for tool_use in response .content .iter() .filter(|block| block_type(block) == "tool_use") { let name = tool_use .get("name") .and_then(Value::as_str) .context("tool_use block has no name")?; let id = tool_use .get("id") .and_then(Value::as_str) .context("tool_use block has no id")?; let input = tool_use.get("input").cloned().unwrap_or(json!({})); // Add information about the tool call to final text final_text.push(format!("[Calling tool {name} with args {input}]")); // Query the MCP server let mut params = CallToolRequestParams::new(name.to_string()); if let Some(arguments) = input.as_object().cloned() { params = params.with_arguments(arguments); } let tool_result = match session.call_tool(params).await { Ok(result) => result, // A rejected call is the model's mistake to correct, so it // goes back as a failed tool_result rather than ending the // query. Every tool_use still needs a matching result. Err(error) => { final_text.push(format!("[{name} failed: {error}]")); tool_results.push(json!({ "type": "tool_result", "tool_use_id": id, "content": format!("Tool call {name} failed: {error}"), "is_error": true, })); continue; } }; self.validate_tool_output(name, &tool_result)?; // structured_content is data the application can use directly. if let Some(Value::Array(items)) = &tool_result.structured_content { final_text.push(format!("[{name} returned {} items]", items.len())); } tool_results.push(json!({ "type": "tool_result", "tool_use_id": id, "content": tool_result_content(&tool_result), "is_error": tool_result.is_error.unwrap_or(false), })); } // Every tool_use needs a matching tool_result, all in one user // message, and the assistant's blocks go back as they arrived. self.messages.push(Message::assistant(response.content)); self.messages.push(Message::user(tool_results)); } Ok(final_text.join("\n")) } /// Call Claude with the current history and return its reply, with the /// content blocks untouched. Tools are passed on every call so Claude can /// keep calling them across turns. async fn request_model(&self, messages: &[Message]) -> Result<MessagesResponse> { let api_key = std::env::var("ANTHROPIC_API_KEY").context("ANTHROPIC_API_KEY is not set")?; // The base URL is configurable for the same reason the official SDKs // make it configurable: to point the client at a local stand-in. let base_url = std::env::var("ANTHROPIC_BASE_URL").unwrap_or_else(|_| ANTHROPIC_API_BASE.to_string()); let request = MessagesRequest { model: MODEL_ANTHROPIC, max_tokens: MAX_TOKENS, system: SYSTEM_PROMPT, messages, tools: &self.tools, }; let response = self .http .post(format!("{}/v1/messages", base_url.trim_end_matches('/'))) .bearer_auth(api_key) .header("anthropic-version", ANTHROPIC_VERSION) .json(&request) .send() .await .context("Anthropi - mcp-client-typescript/index.ts (10127 bytes)
import Anthropic from "@anthropic-ai/sdk"; import { Client, ProtocolError } from "@modelcontextprotocol/client"; import type { CallToolResult } from "@modelcontextprotocol/client"; import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; import readline from "readline/promises"; import dotenv from "dotenv"; dotenv.config({ quiet: true }); // load environment variables from .env const ANTHROPIC_MODEL = "claude-sonnet-5"; // Sonnet 5 thinks adaptively unless told otherwise, and max_tokens caps thinking // plus the reply, so leave room for both. const MAX_TOKENS = 10000; const MAX_TOOL_TURNS = 10; const SYSTEM_PROMPT = "You are a helpful assistant. Use the available tools when they help answer the question."; type ImageMediaType = Anthropic.Base64ImageSource["media_type"]; // Image types the Messages API accepts. const SUPPORTED_IMAGE_TYPES = new Set<string>([ "image/jpeg", "image/png", "image/gif", "image/webp", ] satisfies ImageMediaType[]); /** * Translate an MCP tool result into content for an Anthropic tool_result. * * MCP and Anthropic content blocks differ, so each kind is converted. A kind * the model cannot take becomes a placeholder rather than vanishing, so the * model knows something was there. */ function toolResultContent( result: CallToolResult, ): Array<Anthropic.TextBlockParam | Anthropic.ImageBlockParam> { let content: Array<Anthropic.TextBlockParam | Anthropic.ImageBlockParam> = []; for (const block of result.content) { if (block.type === "text") { content.push({ type: "text", text: block.text }); } else if (block.type === "image" && SUPPORTED_IMAGE_TYPES.has(block.mimeType)) { content.push({ type: "image", source: { type: "base64", media_type: block.mimeType as ImageMediaType, data: block.data, }, }); } else if (block.type === "resource" && "text" in block.resource) { content.push({ type: "text", text: block.resource.text }); } else { content.push({ type: "text", text: `[unsupported result type: ${block.type}]` }); } } content = content.filter((block) => block.type !== "text" || block.text !== ""); if ( result.structuredContent !== undefined && !result.content.some((block) => block.type === "text" && block.text !== "") ) { content.push({ type: "text", text: JSON.stringify(result.structuredContent) }); } return content; } class MCPClient { private mcp: Client; private _anthropic: Anthropic | null = null; private transport: StdioClientTransport | null = null; private tools: Anthropic.Tool[] = []; private messages: Anthropic.MessageParam[] = []; constructor() { // 'auto' probes server/discover, falling back to the 2025-11-25 handshake. // The SDK's default is 'legacy'. this.mcp = new Client( { name: "mcp-client-typescript", version: "1.0.0" }, { versionNegotiation: { mode: "auto" } }, ); } private get anthropic(): Anthropic { // Lazy-initialize Anthropic client when needed return this._anthropic ??= new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY }); } async connectToServer(serverCommand: string[]) { /** * Connect to an MCP server * * @param serverCommand - The command that starts the server, and its arguments */ try { this.transport = new StdioClientTransport({ command: serverCommand[0], args: serverCommand.slice(1), }); await this.mcp.connect(this.transport); // The tools are listed once, here; this client doesn't follow later changes. const toolsResult = await this.mcp.listTools(); this.tools = toolsResult.tools.map((tool) => { return { name: tool.name, description: tool.description, input_schema: tool.inputSchema, }; }); console.log( "Connected to server with tools:", this.tools.map(({ name }) => name), ); } catch (e) { console.log("Failed to connect to MCP server: ", e); throw e; } } async processQuery(query: string) { /** * Process a query using Claude and available tools * * @param query - The user's input query * @returns Processed response as a string */ const historyLength = this.messages.length; this.messages.push({ role: "user", content: query }); const finalText: string[] = []; for (let turn = 0; turn <= MAX_TOOL_TURNS; turn++) { const response = await this.anthropic.messages.create({ model: ANTHROPIC_MODEL, max_tokens: MAX_TOKENS, system: SYSTEM_PROMPT, messages: this.messages, tools: this.tools, }); if (response.stop_reason === "refusal") { // Drop the refused query so a follow-up doesn't send it again. this.messages.length = historyLength; finalText.push("[The model declined to answer; the query is not kept in history]"); break; } for (const block of response.content) { if (block.type === "text") finalText.push(block.text); } if (response.stop_reason === "max_tokens") { finalText.push("[Reply cut off at the max_tokens limit]"); break; } if (response.stop_reason !== "tool_use") { // The API rejects an empty assistant message, so an empty reply isn't kept. if (response.content.length > 0) { this.messages.push({ role: "assistant", content: response.content }); } break; } if (turn === MAX_TOOL_TURNS) { finalText.push(`[Stopped after ${MAX_TOOL_TURNS} tool-use turns]`); break; } const toolResults: Anthropic.ToolResultBlockParam[] = []; for (const toolUse of response.content) { if (toolUse.type !== "tool_use") continue; const toolArgs = toolUse.input as { [x: string]: unknown } | undefined; finalText.push( `[Calling tool ${toolUse.name} with args ${JSON.stringify(toolArgs)}]`, ); let result: CallToolResult; try { // callTool validates the result against the declared schema. result = await this.mcp.callTool({ name: toolUse.name, arguments: toolArgs, }); } catch (error) { if (!(error instanceof ProtocolError)) throw error; // A rejected call is the model's mistake to correct, so it goes back // as a failed tool_result rather than ending the query. Every // tool_use still needs a matching result. finalText.push(`[${toolUse.name} failed: ${error.message}]`); toolResults.push({ type: "tool_result", tool_use_id: toolUse.id, content: `Tool call ${toolUse.name} failed: ${error.message}`, is_error: true, }); continue; } // structuredContent is data the application can use directly. if (Array.isArray(result.structuredContent)) { finalText.push( `[${toolUse.name} returned ${result.structuredContent.length} items]`, ); } toolResults.push({ type: "tool_result", tool_use_id: toolUse.id, content: toolResultContent(result), is_error: result.isError === true, }); } this.messages.push({ role: "assistant", content: response.content }); this.messages.push({ role: "user", content: toolResults }); } return finalText.join("\n"); } async chatLoop() { /** * Run an interactive chat loop */ const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); // rl.question() doesn't reject on stdin EOF on its own; wire its close // event to an AbortSignal so EOF (Ctrl-D) unblocks it. const ac = new AbortController(); const onClose = () => ac.abort(); rl.on("close", onClose); // In a terminal, readline takes Ctrl-C itself; exit at once, as the other clients do. rl.on("SIGINT", () => process.exit(130)); try { console.log("\nMCP Client Started!"); console.log("Type your queries, 'clear' to forget the conversation, or 'quit' to exit."); while (true) { let message: string; try { message = (await rl.question("\nQuery: ", { signal: ac.signal })).trim(); } catch { break; } if (message.toLowerCase() === "quit") break; if (!message) continue; if (message.toLowerCase() === "clear") { this.messages = []; console.log("\nConversation cleared."); continue; } const historyLength = this.messages.length; try { const response = await this.processQuery(message); console.log("\n" + response); } catch (e) { // Drop the failed query so a follow-up doesn't send it again. this.messages.length = historyLength; console.log(`\nError: ${e instanceof Error ? e.message : String(e)}`); } } } finally { rl.off("close", onClose); rl.close(); } } async cleanup() { /** * Clean up resources */ await this.mcp.close(); } } async function main() { if (process.argv.length < 3) { console.error("Usage: node build/index.js <server_command> [args...]"); process.exitCode = 1; return; } const mcpClient = new MCPClient(); try { await mcpClient.connectToServer(process.argv.slice(2)); // Check if we have a valid API key to continue const apiKey = process.env.ANTHROPIC_API_KEY; if (!apiKey) { console.log( "\nNo ANTHROPIC_API_KEY found. To query these tools with Claude, set your API key:" ); console.log(" export ANTHROPIC_API_KEY=your-api-key-here"); return; } await mcpClient.chatLoop(); } catch (e) { console.error("Error:", e); await mcpClient.cleanup(); process.exit(1); } finally { await mcpClient.cleanup(); process.exit(0); } } main(); - mcp-client-typescript/package.json (578 bytes)
{ "name": "mcp-client-typescript", "version": "1.0.0", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "tsc && node -e \"require('fs').chmodSync('build/index.js', '755')\"" }, "keywords": [], "author": "", "license": "ISC", "type": "module", "dependencies": { "@anthropic-ai/sdk": "^1.8.0", "@modelcontextprotocol/client": "^2.4.0", "dotenv": "^18.0.10" }, "devDependencies": { "@types/node": "^24.19.2", "typescript": "^7.0.2" }, "engines": { "node": ">=24.0.0" } } - mcp-client-typescript/README.md (3202 bytes)
# An LLM-Powered Chatbot MCP Client written in TypeScript An interactive chatbot MCP client: it launches an MCP server over stdio, lists its tools, and hands them to Claude, which can call them while answering your questions. This example accompanies the [Build an MCP client](https://modelcontextprotocol.io/docs/develop/build-client) tutorial. ## Prerequisites - Node.js 24+ - npm - An [Anthropic API key](https://console.anthropic.com/) (optional — see below) ## Setup Install dependencies and build, then put your API key in a `.env` file (or export `ANTHROPIC_API_KEY` in your shell): ```bash npm install npm run build cp .env.example .env # then edit .env and add your key ``` ## Run the client Pass the command that starts the server, and its arguments: ```bash node build/index.js node ../weather-server-typescript/build/index.js ``` (Build the server first — see its README.) Type a question (for example, "What's the weather in Sacramento?") and Claude answers using the server's tools. The client keeps the conversation for the whole session, so a follow-up such as "And the alerts for that state?" works. Type `clear` to start a new conversation, or `quit` (or press Ctrl-D) to exit and shut the server down cleanly. Ctrl-C stops the client at once. Without an `ANTHROPIC_API_KEY`, the client still connects, prints the server's tools, and exits — useful for verifying the MCP wiring without credentials. ## Structured content The SDK validates every result against the tool's declared `outputSchema`, so the spec's client-side SHOULD needs no code here. The two channels go to different readers: `content` is forwarded to the model, while `structuredContent` is used as data — when a tool returns an array, the client counts its items rather than re-reading the prose. See [Structured Content](https://modelcontextprotocol.io/specification/draft/server/tools#structured-content). Before a tool result goes to the model, the client converts it to the Messages API's block types. Text stays text, a PNG, JPEG, GIF or WebP image becomes an image block, and a text resource becomes its text. Anything else, such as audio, becomes a placeholder like `[unsupported result type: audio]`, so the model knows something was there. Empty text is dropped, because the Messages API rejects empty text blocks. A result with structured content and no text is sent as its JSON. A call the server rejects goes back to the model as a failed tool result, so it can correct itself, rather than ending the query. Every request sends the same short system prompt. When a reply stops early, the client says so: `[Reply cut off at the max_tokens limit]` when it ran out of tokens, and `[The model declined to answer; the query is not kept in history]` when the model refused. A reply that was cut off, refused, empty or stopped at the tool-turn limit is not added to the history, and a query that fails with an error is dropped from it, so the next request stays valid. `versionNegotiation: { mode: 'auto' }` probes `server/discover` and falls back to the `2025-11-25` handshake; the SDK's default is `'legacy'`. See the [SDK documentation](https://ts.sdk.modelcontextprotocol.io/v2/). - mcp-client-typescript/tsconfig.json (360 bytes)
{ "compilerOptions": { "target": "ES2022", "module": "Node16", "moduleResolution": "Node16", "outDir": "./build", "rootDir": "./", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "types": ["node"], "forceConsistentCasingInFileNames": true }, "include": ["index.ts"], "exclude": ["node_modules"] } - README.md (5416 bytes)
# MCP Quickstart Resources Example servers and clients for the [Model Context Protocol](https://modelcontextprotocol.io) (MCP), in five languages. These are companion examples for two official tutorials: - [Build an MCP server](https://modelcontextprotocol.io/docs/develop/build-server) – a simple MCP weather server exposing two tools backed by the US National Weather Service API - [Build an MCP client](https://modelcontextprotocol.io/docs/develop/build-client) – an LLM-powered chatbot MCP client that connects to any stdio server and lets Claude call its tools ## What's in this repository Each example lives in its own directory with its own README covering prerequisites, setup, and how to run it: | Language | Weather server (MCP server) | Chatbot (MCP client) | |------------|------------------------------------------------------------|----------------------------------------------------| | Python | [`weather-server-python`](./weather-server-python) | [`mcp-client-python`](./mcp-client-python) | | TypeScript | [`weather-server-typescript`](./weather-server-typescript) | [`mcp-client-typescript`](./mcp-client-typescript) | | Go | [`weather-server-go`](./weather-server-go) | [`mcp-client-go`](./mcp-client-go) | | Rust | [`weather-server-rust`](./weather-server-rust) | [`mcp-client-rust`](./mcp-client-rust) | | Ruby | [`weather-server-ruby`](./weather-server-ruby) | [`mcp-client-ruby`](./mcp-client-ruby) | All servers communicate over stdio and expose the same two tools: `get_forecast` and `get_alerts` (or `get-forecast` and `get-alerts` in TypeScript). All clients launch a server, list its tools, and start an interactive chat loop in which Claude can call those tools and the conversation is kept until you type `clear` or `quit`. Each client takes the command that starts the server, plus any arguments. Note: These example clients need an `ANTHROPIC_API_KEY` to operate. Without a key, each client still connects and lists the server's tools before exiting, so you can verify the MCP wiring without credentials. You can mix and match across languages: for example, the Python client can drive the TypeScript server with `uv run client.py node ../weather-server-typescript/build/index.js`. Each client's README shows how to launch its matching server. The [`tests`](./tests) directory contains the smoke tests that run in CI against these examples. See [`tests/README.md`](./tests/README.md) for how they work. ## Prerequisites Each example only needs its own language toolchain. To work across the whole repository (for example, to run the smoke tests) you need: - **Node.js** 24+ and **npm** - **Python** 3.10+ and **uv** - **Go** 1.25+ - **Rust** 1.88+ and **Cargo** - **Ruby** 3.4+ and **Bundler** ## Running the tests ```bash make check ``` `make check` lints every example, rebuilds the compiled ones and runs `./tests/smoke-test.sh`. Run `make help` for the per-language targets. The smoke tests verify that every server starts and answers MCP requests (including validating structured tool results against the schemas each tool advertises), and that every client can connect to a mock server and list tools. They run automatically on every pull request via GitHub Actions. ## Contributing Contributions are welcome. To submit a change: 1. Fork the repository and create a branch from `main`. 2. Make your change. Keep the examples minimal - they exist to teach the protocol, not to be production services. 3. If you change an example's behavior, setup, or dependencies, update that example's README to match. 4. Run `make check` and make sure it passes. See [`AGENTS.md`](./AGENTS.md) for how to keep the examples minimal and in sync. 5. Open a pull request against `main` describing what changed and why. A few conventions to follow, in line with the broader [Model Context Protocol contributing guidelines](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/CONTRIBUTING.md): - **Keep documentation clear, concise, and technically accurate.** Include code examples where appropriate, and test the commands and links you add. - **Disclose AI assistance.** If you used any kind of AI assistance to prepare your contribution, say so in the pull request or issue. See [AI_POLICY.md](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/AI_POLICY.md) for what the disclosure should cover. - **Be respectful.** This project follows the MCP community's [Code of Conduct](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/CODE_OF_CONDUCT.md). Concerns can be reported to [email protected]. ## Security note These examples are intentionally minimal. If you expose an MCP server over a network (HTTP/SSE/WebSocket), add authentication and basic hardening (CORS allowlist, request size limits, timeouts, rate limits, and log redaction). See [`SECURITY.md`](./SECURITY.md). ## License The MCP project is transitioning from the MIT License to Apache-2.0. New code contributions are licensed under Apache-2.0, and documentation (excluding specifications) under CC-BY-4.0. Earlier contributions whose authors have not consented to relicensing remain under the MIT License. See [`LICENSE`](./LICENSE) for the full terms.
- SECURITY.md (1387 bytes)
# Security Notes (Quickstart Resources) These examples are intentionally minimal and optimized for learning. Before using similar patterns in production, apply basic hardening. ## If You Expose An MCP Server Over A Network (HTTP/SSE/WebSocket) - **Require authentication**: do not expose unauthenticated tool endpoints to the public internet. - **Treat browsers as hostile**: - Do not use wildcard CORS (`Access-Control-Allow-Origin: *`) on authenticated endpoints. - Do not reflect `Origin` without allowlist validation. - Prefer an explicit origin allowlist. - **Bound resource usage**: - Set an explicit maximum request body size. - Add timeouts to outbound requests. - Add rate limits (per user/token and/or per IP). - **Avoid RCE primitives in tools**: - Avoid `eval` / dynamic code execution. - Avoid invoking a shell with attacker-controlled input (`exec`, `sh -c`, `shell=True`). - If you must run commands, enforce strict allowlists and pass arguments as arrays (no shell). - **Don't leak secrets**: redact `Authorization`, cookies, and API keys from logs. ## Local-Only Usage If you run these examples locally via stdio transports, your main risks are still: - accidentally adding dangerous tools (filesystem/shell) without strict controls - leaking secrets via logs or environment When in doubt: keep tool capability narrow and add input validation.
- weather-server-go/main.go (8945 bytes)
package main import ( "cmp" "context" "encoding/json" "fmt" "io" "log" "net/http" "strings" "github.com/modelcontextprotocol/go-sdk/mcp" ) const ( NWSAPIBase = "https://api.weather.gov" UserAgent = "weather-app/1.0" ) type ForecastInput struct { Latitude float64 `json:"latitude" jsonschema:"Latitude of the location"` Longitude float64 `json:"longitude" jsonschema:"Longitude of the location"` } type AlertsInput struct { State string `json:"state" jsonschema:"Two-letter US state code (e.g. CA, NY)"` } type PointsResponse struct { Properties struct { Forecast string `json:"forecast"` } `json:"properties"` } type ForecastResponse struct { Properties struct { Periods []ForecastPeriod `json:"periods"` } `json:"properties"` } type ForecastPeriod struct { Name string `json:"name"` Temperature int `json:"temperature"` TemperatureUnit string `json:"temperatureUnit"` WindSpeed string `json:"windSpeed"` WindDirection string `json:"windDirection"` DetailedForecast string `json:"detailedForecast"` } type AlertsResponse struct { Features []AlertFeature `json:"features"` } type AlertFeature struct { Properties AlertProperties `json:"properties"` } type AlertProperties struct { Event string `json:"event"` AreaDesc string `json:"areaDesc"` Severity string `json:"severity"` Description string `json:"description"` Instruction string `json:"instruction"` } // Alerts is get_alerts' structured content. Revision 2026-07-28 allows a // top-level array, but 2025-11-25 clients reject one, and the SDK does not yet // convert it for them, so wrap the list. type Alerts struct { Alerts []Alert `json:"alerts" jsonschema:"Active alerts, empty if there are none"` } // Alert is one element of Alerts. type Alert struct { Event string `json:"event" jsonschema:"The kind of weather event"` Area string `json:"area" jsonschema:"The area the alert covers"` Severity string `json:"severity" jsonschema:"How severe the event is"` Description string `json:"description" jsonschema:"What is happening"` Instructions string `json:"instructions" jsonschema:"What people in the area should do"` } // Period is one element of Forecast's periods. ForecastPeriod above is the // shape NWS sends; this is the shape the tool publishes, kept separate for the // same reason Alert is separate from AlertProperties. type Period struct { Name string `json:"name"` Temperature int `json:"temperature"` TemperatureUnit string `json:"temperature_unit"` WindSpeed string `json:"wind_speed"` WindDirection string `json:"wind_direction"` DetailedForecast string `json:"detailed_forecast"` } // Forecast is get_forecast's structured content. type Forecast struct { Latitude float64 `json:"latitude" jsonschema:"Latitude the forecast is for"` Longitude float64 `json:"longitude" jsonschema:"Longitude the forecast is for"` Periods []Period `json:"periods" jsonschema:"The forecast periods, soonest first"` } func makeNWSRequest[T any](ctx context.Context, url string) (*T, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { return nil, fmt.Errorf("failed to create request: %w", err) } req.Header.Set("User-Agent", UserAgent) req.Header.Set("Accept", "application/geo+json") client := http.DefaultClient resp, err := client.Do(req) if err != nil { return nil, fmt.Errorf("failed to make request to %s: %w", url, err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { body, _ := io.ReadAll(resp.Body) return nil, fmt.Errorf("HTTP error %d: %s", resp.StatusCode, string(body)) } var result T if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { return nil, fmt.Errorf("failed to decode response: %w", err) } return &result, nil } func formatAlert(alert Alert) string { return fmt.Sprintf(` Event: %s Area: %s Severity: %s Description: %s Instructions: %s `, alert.Event, alert.Area, alert.Severity, alert.Description, alert.Instructions) } func formatPeriod(period ForecastPeriod) string { return fmt.Sprintf(` %s: Temperature: %d°%s Wind: %s %s Forecast: %s `, period.Name, period.Temperature, period.TemperatureUnit, period.WindSpeed, period.WindDirection, period.DetailedForecast) } func getForecast(ctx context.Context, req *mcp.CallToolRequest, input ForecastInput) ( *mcp.CallToolResult, Forecast, error, ) { // Get points data pointsURL := fmt.Sprintf("%s/points/%f,%f", NWSAPIBase, input.Latitude, input.Longitude) pointsData, err := makeNWSRequest[PointsResponse](ctx, pointsURL) if err != nil { return nil, Forecast{}, fmt.Errorf("unable to fetch forecast data for this location: %w", err) } // Get forecast data forecastURL := pointsData.Properties.Forecast if forecastURL == "" { return nil, Forecast{}, fmt.Errorf("unable to fetch forecast URL") } forecastData, err := makeNWSRequest[ForecastResponse](ctx, forecastURL) if err != nil { return nil, Forecast{}, fmt.Errorf("unable to fetch detailed forecast: %w", err) } periods := forecastData.Properties.Periods if len(periods) == 0 { return nil, Forecast{}, fmt.Errorf("no forecast periods available") } // Show next 5 periods periods = periods[:min(5, len(periods))] published := make([]Period, 0, len(periods)) for _, period := range periods { published = append(published, Period{ Name: period.Name, Temperature: period.Temperature, TemperatureUnit: period.TemperatureUnit, WindSpeed: period.WindSpeed, WindDirection: period.WindDirection, DetailedForecast: period.DetailedForecast, }) } forecast := Forecast{ Latitude: input.Latitude, Longitude: input.Longitude, Periods: published, } var formatted []string for _, period := range periods { formatted = append(formatted, formatPeriod(period)) } result := &mcp.CallToolResult{ Content: []mcp.Content{ &mcp.TextContent{Text: strings.Join(formatted, "\n---\n")}, }, } return result, forecast, nil } func getAlerts(ctx context.Context, req *mcp.CallToolRequest, input AlertsInput) ( *mcp.CallToolResult, Alerts, error, ) { // Build alerts URL stateCode := strings.ToUpper(input.State) alertsURL := fmt.Sprintf("%s/alerts/active/area/%s", NWSAPIBase, stateCode) alertsData, err := makeNWSRequest[AlertsResponse](ctx, alertsURL) if err != nil { return nil, Alerts{}, fmt.Errorf("unable to fetch alerts for state %s: %w", stateCode, err) } // No alerts is an empty list, not an error. make, not a nil slice, so it // marshals to [] rather than null. alerts := make([]Alert, 0, len(alertsData.Features)) for _, feature := range alertsData.Features { props := feature.Properties alerts = append(alerts, Alert{ Event: cmp.Or(props.Event, "Unknown"), Area: cmp.Or(props.AreaDesc, "Unknown"), Severity: cmp.Or(props.Severity, "Unknown"), Description: cmp.Or(props.Description, "No description available"), Instructions: cmp.Or(props.Instruction, "No specific instructions provided"), }) } text := "No active alerts for this state." if len(alerts) > 0 { var formatted []string for _, alert := range alerts { formatted = append(formatted, formatAlert(alert)) } text = strings.Join(formatted, "\n---\n") } result := &mcp.CallToolResult{ Content: []mcp.Content{&mcp.TextContent{Text: text}}, } return result, Alerts{Alerts: alerts}, nil } // weatherToolAnnotations returns hints for hosts: both tools only read data, // and they read it from an outside service (the NWS API). Hints are not // guarantees; a host decides how far to trust them. func weatherToolAnnotations() *mcp.ToolAnnotations { destructive, openWorld := false, true return &mcp.ToolAnnotations{ ReadOnlyHint: true, DestructiveHint: &destructive, IdempotentHint: true, OpenWorldHint: &openWorld, } } func main() { // Create MCP server. // // Passing an empty Capabilities suppresses the SDK's historical default of // advertising {"logging":{}} — this server does no logging, and the logging // feature is deprecated as of 2026-07-28 (SEP-2577). The tools capability is // still inferred from the tools registered below. server := mcp.NewServer(&mcp.Implementation{ Name: "weather", Version: "1.0.0", }, &mcp.ServerOptions{ Capabilities: &mcp.ServerCapabilities{}, }) // Add get_forecast tool mcp.AddTool(server, &mcp.Tool{ Name: "get_forecast", Description: "Get weather forecast for a location", Annotations: weatherToolAnnotations(), }, getForecast) // Add get_alerts tool mcp.AddTool(server, &mcp.Tool{ Name: "get_alerts", Description: "Get weather alerts for a US state", Annotations: weatherToolAnnotations(), }, getAlerts) // Run server on stdio transport if err := server.Run(context.Background(), &mcp.StdioTransport{}); err != nil { log.Fatal(err) } } - weather-server-go/README.md (2631 bytes)
# A Simple MCP Weather Server written in Go A minimal MCP server that exposes US weather data from the [National Weather Service API](https://www.weather.gov/documentation/services-web-api) as two tools: - `get_forecast` – get the forecast for a location (takes `latitude` and `longitude`) - `get_alerts` – get active weather alerts for a US state (takes a two-letter state code) This example accompanies the [Build an MCP server](https://modelcontextprotocol.io/docs/develop/build-server) tutorial. ## Prerequisites - Go 1.25+ ## Build and run ```bash go build -o weather ./weather ``` The server communicates over stdio, so running it directly just waits for a client on stdin. To see it in action, launch it from one of the client examples in this repository, for example: ```bash cd ../mcp-client-go go run . ../weather-server-go/weather ``` ## Tool annotations Both tools declare the same [annotations](https://modelcontextprotocol.io/specification/2026-07-28/schema#toolannotations): `readOnlyHint: true`, `destructiveHint: false`, `idempotentHint: true` and `openWorldHint: true`. They tell a host that the tools only read data, and that they read it from an outside service (the NWS API), so a host can, for example, run them without asking the user to confirm each call. Annotations are hints, not guarantees: a host should rely on them only for servers it trusts. ## Structured content Both tools advertise an `outputSchema` and return `StructuredContent`, and both return an object: `get_alerts` returns `{"alerts": [...]}`, with an empty list when there are none. Neither tool sets `OutputSchema` on the `Tool`: the SDK infers one from the handler's return type, which is the idiomatic Go spelling. Inference types a slice field as `["null", "array"]`, because a nil slice marshals to `null`; the handlers always build a non-nil slice, so the tools never send `null`. Revision `2026-07-28` is the first to allow a top-level array as the root of an output schema (see [Structured Content](https://modelcontextprotocol.io/specification/2026-07-28/server/tools#structured-content) in the spec), but `2025-11-25` and earlier require an object, and that is still the revision most clients negotiate. This SDK sends an array schema as written on every connection rather than converting it, and an older client rejects it. So all five servers wrap the list in an object, and a `2025-11-25` client sees the same `get_alerts` as a `2026-07-28` one. They can return a bare array once every SDK converts it for older clients; see [#272](https://github.com/modelcontextprotocol/quickstart-resources/issues/272). - weather-server-python/pyproject.toml (1386 bytes)
[project] name = "weather" version = "0.1.0" description = "A simple MCP weather server" readme = "README.md" requires-python = ">=3.10" # httpx2, not httpx: `mcp` already depends on httpx2, so adding httpx would # install a second HTTP stack alongside it. dependencies = [ "httpx2>=2.14.0", "mcp[cli]>=2.3.0", # weather.py imports BaseModel, Field, and RootModel directly. RootModel is v2-only. "pydantic>=2.14.3", ] [build-system] requires = [ "hatchling",] build-backend = "hatchling.build" [dependency-groups] dev = [ "ruff>=0.17.5", ] [project.scripts] weather = "weather:main" [tool.ruff] line-length = 120 target-version = "py310" extend-exclude = ["README.md"] [tool.ruff.lint] select = [ "C4", # flake8-comprehensions "C90", # mccabe "E", # pycodestyle "F", # pyflakes "I", # isort "PERF", # Perflint "PL", # Pylint "UP", # pyupgrade ] ignore = ["PERF203", "PLC0415", "PLR0402"] mccabe.max-complexity = 24 # Default is 10 [tool.ruff.lint.pylint] allow-magic-value-types = ["bytes", "float", "int", "str"] max-args = 23 # Default is 5 max-branches = 23 # Default is 12 max-returns = 13 # Default is 6 max-statements = 102 # Default is 50 - weather-server-python/README.md (2497 bytes)
# A Simple MCP Weather Server written in Python A minimal MCP server that exposes US weather data from the [National Weather Service API](https://www.weather.gov/documentation/services-web-api) as two tools: - `get_forecast` – get the forecast for a location (takes `latitude` and `longitude`) - `get_alerts` – get active weather alerts for a US state (takes a two-letter state code) This example accompanies the [Build an MCP server](https://modelcontextprotocol.io/docs/develop/build-server) tutorial. ## Prerequisites - Python 3.10+ - [uv](https://docs.astral.sh/uv/) ## Run the server ```bash uv run weather.py ``` `uv run` creates the virtual environment and installs dependencies on first use. The server communicates over stdio, so running it directly just waits for a client on stdin. To see it in action, launch it from one of the client examples in this repository, for example: ```bash cd ../mcp-client-python uv run client.py uv --directory ../weather-server-python run weather.py ``` ## Tool annotations Both tools declare the same [annotations](https://modelcontextprotocol.io/specification/2026-07-28/schema#toolannotations): `readOnlyHint: true`, `destructiveHint: false`, `idempotentHint: true` and `openWorldHint: true`. They tell a host that the tools only read data, and that they read it from an outside service (the NWS API), so a host can, for example, run them without asking the user to confirm each call. Annotations are hints, not guarantees: a host should rely on them only for servers it trusts. ## Structured content Both tools declare an output schema and return `structured_content`, and both return an object: `get_alerts` returns `{"alerts": [...]}`, with an empty list when there are none. Revision `2026-07-28` is the first to allow a top-level array as the root of an output schema (see [Structured Content](https://modelcontextprotocol.io/specification/2026-07-28/server/tools#structured-content) in the spec), but `2025-11-25` and earlier require an object, and that is still the revision most clients negotiate. This SDK does not convert an array schema for an older client: `tools/list` fails with an internal error, so the client gets no tools at all. So all five servers wrap the list in an object, and a `2025-11-25` client sees the same `get_alerts` as a `2026-07-28` one. They can return a bare array once every SDK converts it for older clients; see [#272](https://github.com/modelcontextprotocol/quickstart-resources/issues/272). - weather-server-python/weather.py (5409 bytes)
from typing import Any import httpx2 from mcp.server import MCPServer from mcp.server.mcpserver.exceptions import ToolError from mcp.types import ToolAnnotations from pydantic import BaseModel, Field # Initialize the MCP server mcp = MCPServer("weather") # Constants NWS_API_BASE = "https://api.weather.gov" USER_AGENT = "weather-app/1.0" # Hints for hosts: both tools only read data, and they read it from an outside # service (the NWS API). Hints are not guarantees; a host decides how far to # trust them. WEATHER_TOOL_ANNOTATIONS = ToolAnnotations( read_only_hint=True, destructive_hint=False, idempotent_hint=True, open_world_hint=True, ) class Alert(BaseModel): """One active weather alert.""" event: str = Field(description="The kind of weather event") area: str = Field(description="The area the alert covers") severity: str = Field(description="How severe the event is") description: str = Field(description="What is happening") instructions: str = Field(description="What people in the area should do") class Alerts(BaseModel): """The output schema of get_alerts. Revision 2026-07-28 allows a top-level array here, but 2025-11-25 clients reject one, and the SDK does not yet convert it for them, so wrap the list. """ alerts: list[Alert] = Field(description="Active alerts, empty if there are none") class Period(BaseModel): """One period of a forecast.""" name: str = Field(description="Label for the period, e.g. Tonight or Tuesday") temperature: int = Field(description="Forecast temperature") temperature_unit: str = Field(description="Unit of the temperature, F or C") wind_speed: str = Field(description="Wind speed, e.g. 10 to 15 mph") wind_direction: str = Field(description="Wind direction as a compass point") detailed_forecast: str = Field(description="Prose description of the period") class Forecast(BaseModel): """The output schema of get_forecast.""" latitude: float = Field(description="Latitude the forecast is for") longitude: float = Field(description="Longitude the forecast is for") periods: list[Period] = Field(description="The forecast periods, soonest first") async def make_nws_request(url: str) -> dict[str, Any] | None: """Make a request to the NWS API with proper error handling.""" headers = {"User-Agent": USER_AGENT, "Accept": "application/geo+json"} async with httpx2.AsyncClient() as client: try: response = await client.get(url, headers=headers, timeout=30.0) response.raise_for_status() return response.json() except Exception: return None @mcp.tool(annotations=WEATHER_TOOL_ANNOTATIONS) async def get_alerts(state: str) -> Alerts: """Get weather alerts for a US state. Args: state: Two-letter US state code (e.g. CA, NY) """ url = f"{NWS_API_BASE}/alerts/active/area/{state.upper()}" data = await make_nws_request(url) if not data or "features" not in data: raise ToolError(f"Unable to fetch alerts for {state.upper()}.") # No alerts is an empty list, not an error. # # `or` rather than a `get` default: NWS sends these fields as explicit # nulls rather than omitting them, and a default only covers a missing key. return Alerts( alerts=[ Alert( event=props.get("event") or "Unknown", area=props.get("areaDesc") or "Unknown", severity=props.get("severity") or "Unknown", description=props.get("description") or "No description available", instructions=props.get("instruction") or "No specific instructions provided", ) for props in (feature["properties"] for feature in data["features"]) ] ) @mcp.tool(annotations=WEATHER_TOOL_ANNOTATIONS) async def get_forecast(latitude: float, longitude: float) -> Forecast: """Get weather forecast for a location. Args: latitude: Latitude of the location longitude: Longitude of the location """ # First get the forecast grid endpoint points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}" points_data = await make_nws_request(points_url) if not points_data: raise ToolError("Unable to fetch forecast data for this location.") # Get the forecast URL from the points response forecast_url = points_data["properties"]["forecast"] forecast_data = await make_nws_request(forecast_url) if not forecast_data: raise ToolError("Unable to fetch detailed forecast.") periods = forecast_data["properties"]["periods"][:5] # Only show next 5 periods if not periods: raise ToolError("No forecast periods available.") return Forecast( latitude=latitude, longitude=longitude, periods=[ Period( name=period["name"], temperature=period["temperature"], temperature_unit=period["temperatureUnit"], wind_speed=period["windSpeed"], wind_direction=period["windDirection"], detailed_forecast=period["detailedForecast"], ) for period in periods ], ) def main(): # Initialize and run the server mcp.run(transport="stdio") if __name__ == "__main__": main() - weather-server-ruby/README.md (3471 bytes)
# A Simple MCP Weather Server written in Ruby A minimal MCP server that exposes US weather data from the [National Weather Service API](https://www.weather.gov/documentation/services-web-api) as two tools: - `get_forecast` – get the forecast for a location (takes `latitude` and `longitude`) - `get_alerts` – get active weather alerts for a US state (takes a two-letter state code) This example accompanies the [Build an MCP server](https://modelcontextprotocol.io/docs/develop/build-server) tutorial. ## Prerequisites - Ruby 3.4+ - Bundler ## Setup and run ```bash bundle install bundle exec ruby weather.rb ``` The server communicates over stdio, so running it directly just waits for a client on stdin. To see it in action, launch it from the Ruby client example in this repository: ```bash cd ../mcp-client-ruby bundle install bundle exec ruby client.rb ruby ../weather-server-ruby/weather.rb ``` ## Tool annotations Both tools declare the same [annotations](https://modelcontextprotocol.io/specification/2026-07-28/schema#toolannotations): `readOnlyHint: true`, `destructiveHint: false`, `idempotentHint: true` and `openWorldHint: true`. They tell a host that the tools only read data, and that they read it from an outside service (the NWS API), so a host can, for example, run them without asking the user to confirm each call. Annotations are hints, not guarantees: a host should rely on them only for servers it trusts. ## Structured content Both tools declare an `output_schema` and return `structured_content`, and both return an object: `get_alerts` returns `{"alerts": [...]}`, with an empty list when there are none. Revision `2026-07-28` is the first to allow a top-level array as the root of an output schema (see [Structured Content](https://modelcontextprotocol.io/specification/2026-07-28/server/tools#structured-content) in the spec), but `2025-11-25` and earlier require an object, and that is still the revision most clients negotiate. The gem sends an array schema as written rather than converting it, and an older client rejects it. So all five servers wrap the list in an object, and a `2025-11-25` client sees the same `get_alerts` as a `2026-07-28` one. They can return a bare array once every SDK converts it for older clients; see [#272](https://github.com/modelcontextprotocol/quickstart-resources/issues/272). Because a tool that declares an `output_schema` MUST return conforming structured content, the failure paths return an error result rather than a bare text one — error results are exempt from that requirement. "No alerts" is an empty list, not an error. The tools also return a human-readable `content` block, which the SDK leaves alone. ## Known limitation: strict `2026-07-28` clients reject this server The `mcp` gem never emits the `resultType` field on results. The 2026-07-28 schema makes it mandatory — "Servers implementing this protocol version MUST include this field" — so a client that enforces the revision rejects every response, including `tools/list`, before it ever reaches the structured content. There is no way to set it from user code: `MCP::Server` accepts `ttl_ms:` and `cache_scope:` for the SEP-2549 cache hints, but nothing for `resultType`. The gem's own client does not check the field, so the gap is invisible when a Ruby client talks to a Ruby server, and only appears cross-SDK. Until the gem emits `resultType`, this example is verified only against the Ruby client. - weather-server-ruby/weather.rb (7478 bytes)
# frozen_string_literal: true require "json" require "mcp" require "net/http" require "uri" NWS_API_BASE = "https://api.weather.gov" USER_AGENT = "weather-app/1.0" # Hints for hosts: both tools only read data, and they read it from an outside # service (the NWS API). Hints are not guarantees; a host decides how far to # trust them. The gem sends all four hints, so set each one explicitly: its # defaults (destructive, not idempotent) suit a tool that writes. WEATHER_TOOL_ANNOTATIONS = { read_only_hint: true, destructive_hint: false, idempotent_hint: true, open_world_hint: true }.freeze module HelperMethods def make_nws_request(url) uri = URI(url) request = Net::HTTP::Get.new(uri) request["User-Agent"] = USER_AGENT request["Accept"] = "application/geo+json" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, read_timeout: 30) do |http| http.request(request) end raise "HTTP #{response.code}: #{response.message}" unless response.is_a?(Net::HTTPSuccess) JSON.parse(response.body) end def format_alert(alert) <<~ALERT Event: #{alert[:event]} Area: #{alert[:area]} Severity: #{alert[:severity]} Description: #{alert[:description]} Instructions: #{alert[:instructions]} ALERT end # A tool that declares an output schema MUST return conforming structured # content, so a failure path has to be an error result rather than a bare # text one. Error results are exempt from output schema validation. def error_response(text) MCP::Tool::Response.new([{ type: "text", text: text }], error: true) end end class GetAlerts < MCP::Tool extend HelperMethods tool_name "get_alerts" description "Get weather alerts for a US state" annotations(**WEATHER_TOOL_ANNOTATIONS) input_schema( properties: { state: { type: "string", description: "Two-letter US state code (e.g. CA, NY)" } }, required: ["state"] ) # Revision 2026-07-28 allows a top-level array, but 2025-11-25 clients reject # one, and the SDK does not yet convert it for them, so wrap the list. output_schema( properties: { alerts: { type: "array", description: "Active alerts, empty if there are none", items: { type: "object", properties: { event: { type: "string", description: "The kind of weather event" }, area: { type: "string", description: "The area the alert covers" }, severity: { type: "string", description: "How severe the event is" }, description: { type: "string", description: "What is happening" }, instructions: { type: "string", description: "What people in the area should do" } }, required: ["event", "area", "severity", "description", "instructions"] } } }, required: ["alerts"] ) def self.call(state:, server_context: nil) data = begin make_nws_request("#{NWS_API_BASE}/alerts/active/area/#{state.upcase}") rescue => e return error_response("Unable to fetch alerts for #{state.upcase}: #{e.message}") end unless data.is_a?(Hash) && data["features"] return error_response("Unable to fetch alerts for #{state.upcase}.") end # No alerts is an empty list, not an error. alerts = data["features"].map do |feature| properties = feature["properties"] || {} { event: properties["event"] || "Unknown", area: properties["areaDesc"] || "Unknown", severity: properties["severity"] || "Unknown", description: properties["description"] || "No description available", instructions: properties["instruction"] || "No specific instructions provided" } end text = if alerts.empty? "No active alerts for this state." else alerts.map { |alert| format_alert(alert) }.join("\n---\n") end MCP::Tool::Response.new( [{ type: "text", text: text }], structured_content: { alerts: alerts } ) end end class GetForecast < MCP::Tool extend HelperMethods tool_name "get_forecast" description "Get weather forecast for a location" annotations(**WEATHER_TOOL_ANNOTATIONS) input_schema( properties: { latitude: { type: "number", description: "Latitude of the location" }, longitude: { type: "number", description: "Longitude of the location" } }, required: ["latitude", "longitude"] ) output_schema( type: "object", properties: { latitude: { type: "number", description: "Latitude the forecast is for" }, longitude: { type: "number", description: "Longitude the forecast is for" }, periods: { type: "array", description: "The forecast periods, soonest first", items: { type: "object", properties: { name: { type: "string" }, temperature: { type: "integer" }, temperature_unit: { type: "string" }, wind_speed: { type: "string" }, wind_direction: { type: "string" }, detailed_forecast: { type: "string" } }, required: ["name", "temperature", "temperature_unit", "wind_speed", "wind_direction", "detailed_forecast"] } } }, required: ["latitude", "longitude", "periods"] ) def self.call(latitude:, longitude:, server_context: nil) forecast_data = begin # First get the forecast grid endpoint. points_data = make_nws_request("#{NWS_API_BASE}/points/#{latitude},#{longitude}") forecast_url = points_data.dig("properties", "forecast") return error_response("Unable to fetch forecast data for this location.") unless forecast_url make_nws_request(forecast_url) rescue => e return error_response("Unable to fetch forecast data for this location: #{e.message}") end # Only show the next 5 periods. periods = (forecast_data.dig("properties", "periods") || []).first(5) return error_response("No forecast periods available.") if periods.empty? forecast = { latitude: latitude, longitude: longitude, periods: periods.map do |period| { name: period["name"], temperature: period["temperature"], temperature_unit: period["temperatureUnit"], wind_speed: period["windSpeed"], wind_direction: period["windDirection"], detailed_forecast: period["detailedForecast"] } end } text = forecast[:periods].map do |period| <<~FORECAST #{period[:name]}: Temperature: #{period[:temperature]}°#{period[:temperature_unit]} Wind: #{period[:wind_speed]} #{period[:wind_direction]} Forecast: #{period[:detailed_forecast]} FORECAST end.join("\n---\n") MCP::Tool::Response.new( [{ type: "text", text: text }], structured_content: forecast ) end end server = MCP::Server.new( name: "weather", version: "1.0.0", tools: [GetAlerts, GetForecast], # The gem otherwise advertises prompts, resources and logging as well. This # server has only tools, and logging is deprecated as of 2026-07-28 # (SEP-2577). No listChanged: change notifications are delivered over # `subscriptions/listen`, which this server does not serve. capabilities: { tools: {} } ) transport = MCP::Server::Transports::StdioTransport.new(server) transport.open - weather-server-rust/Cargo.toml (341 bytes)
[package] name = "weather" version = "0.1.0" edition = "2024" [dependencies] rmcp = { version = "3.4", features = ["server", "macros", "transport-io"] } tokio = { version = "1.53", features = ["full"] } reqwest = { version = "0.13", features = ["json"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" anyhow = "1.0" - weather-server-rust/README.md (2424 bytes)
# A Simple MCP Weather Server written in Rust A minimal MCP server that exposes US weather data from the [National Weather Service API](https://www.weather.gov/documentation/services-web-api) as two tools: - `get_forecast` – get the forecast for a location (takes `latitude` and `longitude`) - `get_alerts` – get active weather alerts for a US state (takes a two-letter state code) This example accompanies the [Build an MCP server](https://modelcontextprotocol.io/docs/develop/build-server) tutorial. ## Prerequisites - Rust 1.88+ and Cargo ## Build and run ```bash cargo build --release ./target/release/weather ``` Or, during development: ```bash cargo run ``` The server communicates over stdio, so running it directly just waits for a client on stdin. To see it in action, launch it from one of the client examples in this repository, for example: ```bash cd ../mcp-client-rust cargo run -- ../weather-server-rust/target/release/weather ``` ## Tool annotations Both tools declare the same [annotations](https://modelcontextprotocol.io/specification/2026-07-28/schema#toolannotations): `readOnlyHint: true`, `destructiveHint: false`, `idempotentHint: true` and `openWorldHint: true`. They tell a host that the tools only read data, and that they read it from an outside service (the NWS API), so a host can, for example, run them without asking the user to confirm each call. Annotations are hints, not guarantees: a host should rely on them only for servers it trusts. ## Structured content Both tools declare an `output_schema` and return `structured_content`, and both return an object: `get_alerts` returns `{"alerts": [...]}`, with an empty list when there are none. Revision `2026-07-28` is the first to allow a top-level array as the root of an output schema (see [Structured Content](https://modelcontextprotocol.io/specification/2026-07-28/server/tools#structured-content) in the spec), but `2025-11-25` and earlier require an object, and that is still the revision most clients negotiate. rmcp sends an array schema as written on every connection rather than converting it, and an older client rejects it. So all five servers wrap the list in an object, and a `2025-11-25` client sees the same `get_alerts` as a `2026-07-28` one. They can return a bare array once every SDK converts it for older clients; see [#272](https://github.com/modelcontextprotocol/quickstart-resources/issues/272). - weather-server-rust/src/main.rs (9597 bytes)
use anyhow::Result; use rmcp::{ ErrorData, ServerHandler, ServiceExt, handler::server::{router::tool::ToolRouter, tool::schema_for_output, wrapper::Parameters}, model::*, schemars::{self, JsonSchema}, tool, tool_handler, tool_router, transport::stdio, }; use serde::Deserialize; use serde::Serialize; use serde::de::DeserializeOwned; const NWS_API_BASE: &str = "https://api.weather.gov"; const USER_AGENT: &str = "weather-app/1.0"; #[derive(Debug, Deserialize)] struct AlertsResponse { features: Vec<AlertFeature>, } #[derive(Debug, Deserialize)] struct AlertFeature { properties: AlertProperties, } #[derive(Debug, Deserialize)] struct AlertProperties { event: Option<String>, #[serde(rename = "areaDesc")] area_desc: Option<String>, severity: Option<String>, description: Option<String>, instruction: Option<String>, } #[derive(Debug, Deserialize)] struct PointsResponse { properties: PointsProperties, } #[derive(Debug, Deserialize)] struct PointsProperties { forecast: String, } #[derive(Debug, Deserialize)] struct ForecastResponse { properties: ForecastProperties, } #[derive(Debug, Deserialize)] struct ForecastProperties { periods: Vec<ForecastPeriod>, } #[derive(Debug, Deserialize)] struct ForecastPeriod { name: String, temperature: i32, #[serde(rename = "temperatureUnit")] temperature_unit: String, #[serde(rename = "windSpeed")] wind_speed: String, #[serde(rename = "windDirection")] wind_direction: String, #[serde(rename = "detailedForecast")] detailed_forecast: String, } /// `get_alerts`' structured content. Revision 2026-07-28 allows a top-level /// array, but 2025-11-25 clients reject one, and rmcp does not yet convert it /// for them, so wrap the list. #[derive(Debug, Serialize, JsonSchema)] pub struct Alerts { /// Active alerts, empty if there are none. alerts: Vec<Alert>, } /// One element of `Alerts`. #[derive(Debug, Serialize, JsonSchema)] pub struct Alert { /// The kind of weather event. event: String, /// The area the alert covers. area: String, /// How severe the event is. severity: String, /// What is happening. description: String, /// What people in the area should do. instructions: String, } /// `get_forecast`' structured content. #[derive(Debug, Serialize, JsonSchema)] pub struct Forecast { /// Latitude the forecast is for. latitude: f32, /// Longitude the forecast is for. longitude: f32, /// The forecast periods, soonest first. periods: Vec<Period>, } #[derive(Debug, Serialize, JsonSchema)] pub struct Period { name: String, temperature: i32, temperature_unit: String, wind_speed: String, wind_direction: String, detailed_forecast: String, } async fn make_nws_request<T: DeserializeOwned>(url: &str) -> Result<T> { let client = reqwest::Client::new(); let rsp = client .get(url) .header(reqwest::header::USER_AGENT, USER_AGENT) .header(reqwest::header::ACCEPT, "application/geo+json") .send() .await? .error_for_status()?; Ok(rsp.json::<T>().await?) } fn format_alert(alert: &Alert) -> String { format!( "Event: {}\nArea: {}\nSeverity: {}\nDescription: {}\nInstructions: {}", alert.event, alert.area, alert.severity, alert.description, alert.instructions ) } fn format_period(period: &Period) -> String { format!( "{}:\nTemperature: {}°{}\nWind: {} {}\nForecast: {}", period.name, period.temperature, period.temperature_unit, period.wind_speed, period.wind_direction, period.detailed_forecast ) } /// Build a result carrying both channels. fn dual_channel_result( text: String, structured: impl Serialize, ) -> Result<CallToolResult, ErrorData> { let value = serde_json::to_value(structured).map_err(|e| { ErrorData::internal_error(format!("failed to serialize structured content: {e}"), None) })?; let mut result = CallToolResult::success(vec![ContentBlock::text(text)]); result.structured_content = Some(value); Ok(result) } #[derive(serde::Deserialize, JsonSchema)] pub struct MCPForecastRequest { /// Latitude of the location. latitude: f32, /// Longitude of the location. longitude: f32, } #[derive(serde::Deserialize, JsonSchema)] pub struct MCPAlertRequest { /// Two-letter US state code (e.g. CA, NY). state: String, } #[derive(Clone)] pub struct Weather { tool_router: ToolRouter<Weather>, } // Both tools carry the same annotations, hints for hosts: they only read data, // and they read it from an outside service (the NWS API). Hints are not // guarantees; a host decides how far to trust them. #[tool_router(router = tool_router)] impl Weather { fn new() -> Self { Self { tool_router: Self::tool_router(), } } #[tool( description = "Get weather alerts for a US state.", annotations( read_only_hint = true, destructive_hint = false, idempotent_hint = true, open_world_hint = true ), output_schema = schema_for_output::<Alerts>() )] async fn get_alerts( &self, Parameters(MCPAlertRequest { state }): Parameters<MCPAlertRequest>, ) -> Result<CallToolResult, ErrorData> { let state = state.to_uppercase(); let url = format!("{NWS_API_BASE}/alerts/active/area/{state}"); let Ok(data) = make_nws_request::<AlertsResponse>(&url).await else { return Ok(CallToolResult::error(vec![ContentBlock::text(format!( "Unable to fetch alerts for {state}." ))])); }; // No alerts is an empty list, not an error. let alerts: Vec<Alert> = data .features .into_iter() .map(|feature| { let props = feature.properties; Alert { event: props.event.unwrap_or_else(|| "Unknown".into()), area: props.area_desc.unwrap_or_else(|| "Unknown".into()), severity: props.severity.unwrap_or_else(|| "Unknown".into()), description: props .description .unwrap_or_else(|| "No description available".into()), instructions: props .instruction .unwrap_or_else(|| "No specific instructions provided".into()), } }) .collect(); let text = if alerts.is_empty() { "No active alerts for this state.".to_string() } else { alerts .iter() .map(format_alert) .collect::<Vec<_>>() .join("\n---\n") }; dual_channel_result(text, Alerts { alerts }) } #[tool( description = "Get weather forecast for a location.", annotations( read_only_hint = true, destructive_hint = false, idempotent_hint = true, open_world_hint = true ), output_schema = schema_for_output::<Forecast>() )] async fn get_forecast( &self, Parameters(MCPForecastRequest { latitude, longitude, }): Parameters<MCPForecastRequest>, ) -> Result<CallToolResult, ErrorData> { let points_url = format!("{NWS_API_BASE}/points/{latitude},{longitude}"); let Ok(points_data) = make_nws_request::<PointsResponse>(&points_url).await else { return Ok(CallToolResult::error(vec![ContentBlock::text( "Unable to fetch forecast data for this location.", )])); }; let forecast_url = points_data.properties.forecast; let Ok(forecast_data) = make_nws_request::<ForecastResponse>(&forecast_url).await else { return Ok(CallToolResult::error(vec![ContentBlock::text( "Unable to fetch detailed forecast.", )])); }; let forecast = Forecast { latitude, longitude, periods: forecast_data .properties .periods .into_iter() .take(5) // Next 5 periods only .map(|p| Period { name: p.name, temperature: p.temperature, temperature_unit: p.temperature_unit, wind_speed: p.wind_speed, wind_direction: p.wind_direction, detailed_forecast: p.detailed_forecast, }) .collect(), }; let text = forecast .periods .iter() .map(format_period) .collect::<Vec<_>>() .join("\n---\n"); dual_channel_result(text, &forecast) } } #[tool_handler(router = self.tool_router)] impl ServerHandler for Weather { fn get_info(&self) -> ServerConfig { let mut info = ServerConfig::default(); // Without this the server reports rmcp's own crate name and version // rather than its own. info.server_info = Implementation::new("weather", "1.0.0"); info.capabilities = ServerCapabilities::builder().enable_tools().build(); info } } #[tokio::main] async fn main() -> Result<()> { let service = Weather::new().serve(stdio()).await?; service.waiting().await?; Ok(()) } - weather-server-typescript/package.json (576 bytes)
{ "name": "mcp-quickstart-ts", "version": "1.0.0", "main": "index.js", "type": "module", "bin": { "weather": "./build/index.js" }, "scripts": { "build": "tsc && node -e \"require('fs').chmodSync('build/index.js', '755')\"" }, "files": [ "build" ], "keywords": [], "author": "", "license": "ISC", "description": "", "devDependencies": { "@types/node": "^24.13.4", "typescript": "^7.0.2" }, "dependencies": { "@modelcontextprotocol/server": "^2.0.0", "zod": "^4.6.5" }, "engines": { "node": ">=24.0.0" } } - weather-server-typescript/README.md (2647 bytes)
# A Simple MCP Weather Server written in TypeScript A minimal MCP server that exposes US weather data from the [National Weather Service API](https://www.weather.gov/documentation/services-web-api) as two tools: - `get-forecast` – get the forecast for a location (takes `latitude` and `longitude`) - `get-alerts` – get active weather alerts for a US state (takes a two-letter state code) This example accompanies the [Build an MCP server](https://modelcontextprotocol.io/docs/develop/build-server) tutorial. ## Prerequisites - Node.js 24+ - npm ## Build and run ```bash npm install npm run build node build/index.js ``` The server communicates over stdio, so running it directly just waits for a client on stdin. To see it in action, launch it from one of the client examples in this repository, for example: ```bash cd ../mcp-client-typescript npm install && npm run build node build/index.js node ../weather-server-typescript/build/index.js ``` ## Tool annotations Both tools declare the same [annotations](https://modelcontextprotocol.io/specification/2026-07-28/schema#toolannotations): `readOnlyHint: true`, `destructiveHint: false`, `idempotentHint: true` and `openWorldHint: true`. They tell a host that the tools only read data, and that they read it from an outside service (the NWS API), so a host can, for example, run them without asking the user to confirm each call. Annotations are hints, not guarantees: a host should rely on them only for servers it trusts. ## Structured content Both tools declare an `outputSchema` and return `structuredContent`, and both return an object: `get-alerts` returns `{"alerts": [...]}`, with an empty list when there are none. Revision `2026-07-28` is the first to allow a top-level array as the root of an output schema (see [Structured Content](https://modelcontextprotocol.io/specification/2026-07-28/server/tools#structured-content) in the spec), but `2025-11-25` and earlier require an object, and that is still the revision most clients negotiate. This SDK would cope with an array: it wraps one as `{"result": [...]}` for a `2025-11-25` client. The other four SDKs send it as written, which older clients reject, and the five examples should behave the same. So all five servers wrap the list in an object, and a `2025-11-25` client sees the same `get_alerts` as a `2026-07-28` one. They can return a bare array once every SDK converts it for older clients; see [#272](https://github.com/modelcontextprotocol/quickstart-resources/issues/272). `serveStdio` serves both protocol eras from one factory. See the [SDK documentation](https://ts.sdk.modelcontextprotocol.io/v2/). - weather-server-typescript/src/index.ts (7972 bytes)
import { McpServer } from "@modelcontextprotocol/server"; import { serveStdio } from "@modelcontextprotocol/server/stdio"; import * as z from "zod/v4"; const NWS_API_BASE = "https://api.weather.gov"; const USER_AGENT = "weather-app/1.0"; // Helper function for making NWS API requests async function makeNWSRequest<T>(url: string): Promise<T | null> { const headers = { "User-Agent": USER_AGENT, Accept: "application/geo+json", }; try { const response = await fetch(url, { headers }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return (await response.json()) as T; } catch (error) { console.error("Error making NWS request:", error); return null; } } interface AlertFeature { properties: { event?: string; areaDesc?: string; severity?: string; description?: string; instruction?: string; }; } interface ForecastPeriod { name?: string; temperature?: number; temperatureUnit?: string; windSpeed?: string; windDirection?: string; detailedForecast?: string; } interface AlertsResponse { features: AlertFeature[]; } interface PointsResponse { properties: { forecast?: string; }; } interface ForecastResponse { properties: { periods: ForecastPeriod[]; }; } /** * The output schema of `get-alerts`. Revision 2026-07-28 allows a top-level * array, but the other SDKs still send one to 2025-11-25 clients, which reject * it, so all five servers wrap the list in an object for now. */ const alertsOutputSchema = z.object({ alerts: z .array( z.object({ event: z.string().describe("The kind of weather event"), area: z.string().describe("The area the alert covers"), severity: z.string().describe("How severe the event is"), description: z.string().describe("What is happening"), instructions: z.string().describe("What people in the area should do"), }), ) .describe("Active alerts, empty if there are none"), }); /** The output schema of `get-forecast`. */ const forecastOutputSchema = z.object({ latitude: z.number().describe("Latitude the forecast is for"), longitude: z.number().describe("Longitude the forecast is for"), periods: z .array( z.object({ name: z.string(), temperature: z.number().nullable(), temperature_unit: z.string(), wind_speed: z.string(), wind_direction: z.string(), detailed_forecast: z.string(), }), ) .describe("The forecast periods, soonest first"), }); type Alert = z.infer<typeof alertsOutputSchema>["alerts"][number]; type Forecast = z.infer<typeof forecastOutputSchema>; // Format alert data for the model to read function formatAlert(alert: Alert): string { return [ `Event: ${alert.event}`, `Area: ${alert.area}`, `Severity: ${alert.severity}`, `Description: ${alert.description}`, `Instructions: ${alert.instructions}`, "---", ].join("\n"); } function formatPeriod(period: Forecast["periods"][number]): string { return [ `${period.name}:`, period.temperature === null ? "Temperature: Unknown" : `Temperature: ${period.temperature}°${period.temperature_unit}`, `Wind: ${period.wind_speed} ${period.wind_direction}`, period.detailed_forecast, "---", ].join("\n"); } // Hints for hosts: both tools only read data, and they read it from an outside // service (the NWS API). Hints are not guarantees; a host decides how far to // trust them. const weatherToolAnnotations = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true, }; function buildServer(): McpServer { const server = new McpServer({ name: "weather", version: "1.0.0", }); server.registerTool( "get-alerts", { title: "Get Weather Alerts", annotations: weatherToolAnnotations, description: "Get weather alerts for a state", inputSchema: z.object({ state: z .string() .length(2) .describe("Two-letter state code (e.g. CA, NY)"), }), outputSchema: alertsOutputSchema, }, async ({ state }) => { const stateCode = state.toUpperCase(); const alertsUrl = `${NWS_API_BASE}/alerts/active/area/${stateCode}`; const alertsData = await makeNWSRequest<AlertsResponse>(alertsUrl); if (!alertsData) { throw new Error(`Failed to retrieve alerts data for ${stateCode}`); } // No alerts is an empty list, not an error. // `??` catches the nulls NWS sends for these fields; it does not omit // them, so a key-missing default would not fire. const alerts: Alert[] = (alertsData.features ?? []).map((feature) => ({ event: feature.properties.event ?? "Unknown", area: feature.properties.areaDesc ?? "Unknown", severity: feature.properties.severity ?? "Unknown", description: feature.properties.description ?? "No description available", instructions: feature.properties.instruction ?? "No specific instructions provided", })); const text = alerts.length === 0 ? `No active alerts for ${stateCode}` : `Active alerts for ${stateCode}:\n\n${alerts.map(formatAlert).join("\n")}`; return { content: [{ type: "text", text }], structuredContent: { alerts } }; }, ); server.registerTool( "get-forecast", { title: "Get Weather Forecast", annotations: weatherToolAnnotations, description: "Get weather forecast for a location", inputSchema: z.object({ latitude: z .number() .min(-90) .max(90) .describe("Latitude of the location"), longitude: z .number() .min(-180) .max(180) .describe("Longitude of the location"), }), outputSchema: forecastOutputSchema, }, async ({ latitude, longitude }) => { // Get grid point data const pointsUrl = `${NWS_API_BASE}/points/${latitude.toFixed(4)},${longitude.toFixed(4)}`; const pointsData = await makeNWSRequest<PointsResponse>(pointsUrl); if (!pointsData) { throw new Error( `Failed to retrieve grid point data for coordinates: ${latitude}, ${longitude}. This location may not be supported by the NWS API (only US locations are supported).`, ); } const forecastUrl = pointsData.properties?.forecast; if (!forecastUrl) { throw new Error("Failed to get forecast URL from grid point data"); } // Get forecast data const forecastData = await makeNWSRequest<ForecastResponse>(forecastUrl); if (!forecastData) { throw new Error("Failed to retrieve forecast data"); } const rawPeriods = forecastData.properties?.periods ?? []; if (rawPeriods.length === 0) { throw new Error("No forecast periods available"); } const forecast: Forecast = { latitude, longitude, // Only show the next 5 periods. periods: rawPeriods.slice(0, 5).map((period) => ({ name: period.name ?? "Unknown", temperature: period.temperature ?? null, temperature_unit: period.temperatureUnit ?? "F", wind_speed: period.windSpeed ?? "Unknown", wind_direction: period.windDirection ?? "Unknown", detailed_forecast: period.detailedForecast ?? "No forecast available", })), }; const text = `Forecast for ${latitude}, ${longitude}:\n\n${forecast.periods .map(formatPeriod) .join("\n")}`; return { content: [{ type: "text", text }], structuredContent: forecast }; }, ); return server; } // One factory serves both protocol eras. serveStdio(buildServer, { onerror: (error) => { console.error("Weather MCP Server error:", error); }, }); console.error("Weather MCP Server running on stdio"); - weather-server-typescript/tsconfig.json (363 bytes)
{ "compilerOptions": { "target": "ES2022", "module": "Node16", "moduleResolution": "Node16", "outDir": "./build", "rootDir": "./src", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "types": ["node"], "forceConsistentCasingInFileNames": true }, "include": ["src/**/*"], "exclude": ["node_modules"] }