{"kind":"Skill","metadata":{"namespace":"community","name":"mcp-builder","version":"0.1.0"},"spec":{"description":"Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).","files":{"LICENSE.txt":"\n                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright 2026 Anthropic, PBC.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.","SKILL.md":"---\nname: mcp-builder\ndescription: Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).\nlicense: Complete terms in LICENSE.txt\n---\n\n# MCP Server Development Guide\n\n## Overview\n\nCreate MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. The quality of an MCP server is measured by how well it enables LLMs to accomplish real-world tasks.\n\n---\n\n# Process\n\n## 🚀 High-Level Workflow\n\nCreating a high-quality MCP server involves four main phases:\n\n### Phase 1: Deep Research and Planning\n\n#### 1.1 Understand Modern MCP Design\n\n**API Coverage vs. Workflow Tools:**\nBalance comprehensive API endpoint coverage with specialized workflow tools. Workflow tools can be more convenient for specific tasks, while comprehensive coverage gives agents flexibility to compose operations. Performance varies by client—some clients benefit from code execution that combines basic tools, while others work better with higher-level workflows. When uncertain, prioritize comprehensive API coverage.\n\n**Tool Naming and Discoverability:**\nClear, descriptive tool names help agents find the right tools quickly. Use consistent prefixes (e.g., `github_create_issue`, `github_list_repos`) and action-oriented naming.\n\n**Context Management:**\nAgents benefit from concise tool descriptions and the ability to filter/paginate results. Design tools that return focused, relevant data. Some clients support code execution which can help agents filter and process data efficiently.\n\n**Actionable Error Messages:**\nError messages should guide agents toward solutions with specific suggestions and next steps.\n\n#### 1.2 Study MCP Protocol Documentation\n\n**Navigate the MCP specification:**\n\nStart with the sitemap to find relevant pages: `https://modelcontextprotocol.io/sitemap.xml`\n\nThen fetch specific pages with `.md` suffix for markdown format (e.g., `https://modelcontextprotocol.io/specification/draft.md`).\n\nKey pages to review:\n- Specification overview and architecture\n- Transport mechanisms (streamable HTTP, stdio)\n- Tool, resource, and prompt definitions\n\n#### 1.3 Study Framework Documentation\n\n**Recommended stack:**\n- **Language**: TypeScript (high-quality SDK support and good compatibility in many execution environments e.g. MCPB. Plus AI models are good at generating TypeScript code, benefiting from its broad usage, static typing and good linting tools)\n- **Transport**: Streamable HTTP for remote servers, using stateless JSON (simpler to scale and maintain, as opposed to stateful sessions and streaming responses). stdio for local servers.\n\n**Load framework documentation:**\n\n- **MCP Best Practices**: [📋 View Best Practices](./reference/mcp_best_practices.md) - Core guidelines\n\n**For TypeScript (recommended):**\n- **TypeScript SDK**: Use WebFetch to load `https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/main/README.md`\n- [⚡ TypeScript Guide](./reference/node_mcp_server.md) - TypeScript patterns and examples\n\n**For Python:**\n- **Python SDK**: Use WebFetch to load `https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.md`\n- [🐍 Python Guide](./reference/python_mcp_server.md) - Python patterns and examples\n\n#### 1.4 Plan Your Implementation\n\n**Understand the API:**\nReview the service's API documentation to identify key endpoints, authentication requirements, and data models. Use web search and WebFetch as needed.\n\n**Tool Selection:**\nPrioritize comprehensive API coverage. List endpoints to implement, starting with the most common operations.\n\n---\n\n### Phase 2: Implementation\n\n#### 2.1 Set Up Project Structure\n\nSee language-specific guides for project setup:\n- [⚡ TypeScript Guide](./reference/node_mcp_server.md) - Project structure, package.json, tsconfig.json\n- [🐍 Python Guide](./reference/python_mcp_server.md) - Module organization, dependencies\n\n#### 2.2 Implement Core Infrastructure\n\nCreate shared utilities:\n- API client with authentication\n- Error handling helpers\n- Response formatting (JSON/Markdown)\n- Pagination support\n\n#### 2.3 Implement Tools\n\nFor each tool:\n\n**Input Schema:**\n- Use Zod (TypeScript) or Pydantic (Python)\n- Include constraints and clear descriptions\n- Add examples in field descriptions\n\n**Output Schema:**\n- Define `outputSchema` where possible for structured data\n- Use `structuredContent` in tool responses (TypeScript SDK feature)\n- Helps clients understand and process tool outputs\n\n**Tool Description:**\n- Concise summary of functionality\n- Parameter descriptions\n- Return type schema\n\n**Implementation:**\n- Async/await for I/O operations\n- Proper error handling with actionable messages\n- Support pagination where applicable\n- Return both text content and structured data when using modern SDKs\n\n**Annotations:**\n- `readOnlyHint`: true/false\n- `destructiveHint`: true/false\n- `idempotentHint`: true/false\n- `openWorldHint`: true/false\n\n---\n\n### Phase 3: Review and Test\n\n#### 3.1 Code Quality\n\nReview for:\n- No duplicated code (DRY principle)\n- Consistent error handling\n- Full type coverage\n- Clear tool descriptions\n\n#### 3.2 Build and Test\n\n**TypeScript:**\n- Run `npm run build` to verify compilation\n- Test with MCP Inspector: `npx @modelcontextprotocol/inspector`\n\n**Python:**\n- Verify syntax: `python -m py_compile your_server.py`\n- Test with MCP Inspector\n\nSee language-specific guides for detailed testing approaches and quality checklists.\n\n---\n\n### Phase 4: Create Evaluations\n\nAfter implementing your MCP server, create comprehensive evaluations to test its effectiveness.\n\n**Load [✅ Evaluation Guide](./reference/evaluation.md) for complete evaluation guidelines.**\n\n#### 4.1 Understand Evaluation Purpose\n\nUse evaluations to test whether LLMs can effectively use your MCP server to answer realistic, complex questions.\n\n#### 4.2 Create 10 Evaluation Questions\n\nTo create effective evaluations, follow the process outlined in the evaluation guide:\n\n1. **Tool Inspection**: List available tools and understand their capabilities\n2. **Content Exploration**: Use READ-ONLY operations to explore available data\n3. **Question Generation**: Create 10 complex, realistic questions\n4. **Answer Verification**: Solve each question yourself to verify answers\n\n#### 4.3 Evaluation Requirements\n\nEnsure each question is:\n- **Independent**: Not dependent on other questions\n- **Read-only**: Only non-destructive operations required\n- **Complex**: Requiring multiple tool calls and deep exploration\n- **Realistic**: Based on real use cases humans would care about\n- **Verifiable**: Single, clear answer that can be verified by string comparison\n- **Stable**: Answer won't change over time\n\n#### 4.4 Output Format\n\nCreate an XML file with this structure:\n\n```xml\n\u003cevaluation\u003e\n  \u003cqa_pair\u003e\n    \u003cquestion\u003eFind discussions about AI model launches with animal codenames. One model needed a specific safety designation that uses the format ASL-X. What number X was being determined for the model named after a spotted wild cat?\u003c/question\u003e\n    \u003canswer\u003e3\u003c/answer\u003e\n  \u003c/qa_pair\u003e\n\u003c!-- More qa_pairs... --\u003e\n\u003c/evaluation\u003e\n```\n\n---\n\n# Reference Files\n\n## 📚 Documentation Library\n\nLoad these resources as needed during development:\n\n### Core MCP Documentation (Load First)\n- **MCP Protocol**: Start with sitemap at `https://modelcontextprotocol.io/sitemap.xml`, then fetch specific pages with `.md` suffix\n- [📋 MCP Best Practices](./reference/mcp_best_practices.md) - Universal MCP guidelines including:\n  - Server and tool naming conventions\n  - Response format guidelines (JSON vs Markdown)\n  - Pagination best practices\n  - Transport selection (streamable HTTP vs stdio)\n  - Security and error handling standards\n\n### SDK Documentation (Load During Phase 1/2)\n- **Python SDK**: Fetch from `https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.md`\n- **TypeScript SDK**: Fetch from `https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/main/README.md`\n\n### Language-Specific Implementation Guides (Load During Phase 2)\n- [🐍 Python Implementation Guide](./reference/python_mcp_server.md) - Complete Python/FastMCP guide with:\n  - Server initialization patterns\n  - Pydantic model examples\n  - Tool registration with `@mcp.tool`\n  - Complete working examples\n  - Quality checklist\n\n- [⚡ TypeScript Implementation Guide](./reference/node_mcp_server.md) - Complete TypeScript guide with:\n  - Project structure\n  - Zod schema patterns\n  - Tool registration with `server.registerTool`\n  - Complete working examples\n  - Quality checklist\n\n### Evaluation Guide (Load During Phase 4)\n- [✅ Evaluation Guide](./reference/evaluation.md) - Complete evaluation creation guide with:\n  - Question creation guidelines\n  - Answer verification strategies\n  - XML format specifications\n  - Example questions and answers\n  - Running an evaluation with the provided scripts\n","reference/evaluation.md":"# MCP Server Evaluation Guide\n\n## Overview\n\nThis document provides guidance on creating comprehensive evaluations for MCP servers. Evaluations test whether LLMs can effectively use your MCP server to answer realistic, complex questions using only the tools provided.\n\n---\n\n## Quick Reference\n\n### Evaluation Requirements\n- Create 10 human-readable questions\n- Questions must be READ-ONLY, INDEPENDENT, NON-DESTRUCTIVE\n- Each question requires multiple tool calls (potentially dozens)\n- Answers must be single, verifiable values\n- Answers must be STABLE (won't change over time)\n\n### Output Format\n```xml\n\u003cevaluation\u003e\n   \u003cqa_pair\u003e\n      \u003cquestion\u003eYour question here\u003c/question\u003e\n      \u003canswer\u003eSingle verifiable answer\u003c/answer\u003e\n   \u003c/qa_pair\u003e\n\u003c/evaluation\u003e\n```\n\n---\n\n## Purpose of Evaluations\n\nThe measure of quality of an MCP server is NOT how well or comprehensively the server implements tools, but how well these implementations (input/output schemas, docstrings/descriptions, functionality) enable LLMs with no other context and access ONLY to the MCP servers to answer realistic and difficult questions.\n\n## Evaluation Overview\n\nCreate 10 human-readable questions requiring ONLY READ-ONLY, INDEPENDENT, NON-DESTRUCTIVE, and IDEMPOTENT operations to answer. Each question should be:\n- Realistic\n- Clear and concise\n- Unambiguous\n- Complex, requiring potentially dozens of tool calls or steps\n- Answerable with a single, verifiable value that you identify in advance\n\n## Question Guidelines\n\n### Core Requirements\n\n1. **Questions MUST be independent**\n   - Each question should NOT depend on the answer to any other question\n   - Should not assume prior write operations from processing another question\n\n2. **Questions MUST require ONLY NON-DESTRUCTIVE AND IDEMPOTENT tool use**\n   - Should not instruct or require modifying state to arrive at the correct answer\n\n3. **Questions must be REALISTIC, CLEAR, CONCISE, and COMPLEX**\n   - Must require another LLM to use multiple (potentially dozens of) tools or steps to answer\n\n### Complexity and Depth\n\n4. **Questions must require deep exploration**\n   - Consider multi-hop questions requiring multiple sub-questions and sequential tool calls\n   - Each step should benefit from information found in previous questions\n\n5. **Questions may require extensive paging**\n   - May need paging through multiple pages of results\n   - May require querying old data (1-2 years out-of-date) to find niche information\n   - The questions must be DIFFICULT\n\n6. **Questions must require deep understanding**\n   - Rather than surface-level knowledge\n   - May pose complex ideas as True/False questions requiring evidence\n   - May use multiple-choice format where LLM must search different hypotheses\n\n7. **Questions must not be solvable with straightforward keyword search**\n   - Do not include specific keywords from the target content\n   - Use synonyms, related concepts, or paraphrases\n   - Require multiple searches, analyzing multiple related items, extracting context, then deriving the answer\n\n### Tool Testing\n\n8. **Questions should stress-test tool return values**\n   - May elicit tools returning large JSON objects or lists, overwhelming the LLM\n   - Should require understanding multiple modalities of data:\n     - IDs and names\n     - Timestamps and datetimes (months, days, years, seconds)\n     - File IDs, names, extensions, and mimetypes\n     - URLs, GIDs, etc.\n   - Should probe the tool's ability to return all useful forms of data\n\n9. **Questions should MOSTLY reflect real human use cases**\n   - The kinds of information retrieval tasks that HUMANS assisted by an LLM would care about\n\n10. **Questions may require dozens of tool calls**\n    - This challenges LLMs with limited context\n    - Encourages MCP server tools to reduce information returned\n\n11. **Include ambiguous questions**\n    - May be ambiguous OR require difficult decisions on which tools to call\n    - Force the LLM to potentially make mistakes or misinterpret\n    - Ensure that despite AMBIGUITY, there is STILL A SINGLE VERIFIABLE ANSWER\n\n### Stability\n\n12. **Questions must be designed so the answer DOES NOT CHANGE**\n    - Do not ask questions that rely on \"current state\" which is dynamic\n    - For example, do not count:\n      - Number of reactions to a post\n      - Number of replies to a thread\n      - Number of members in a channel\n\n13. **DO NOT let the MCP server RESTRICT the kinds of questions you create**\n    - Create challenging and complex questions\n    - Some may not be solvable with the available MCP server tools\n    - Questions may require specific output formats (datetime vs. epoch time, JSON vs. MARKDOWN)\n    - Questions may require dozens of tool calls to complete\n\n## Answer Guidelines\n\n### Verification\n\n1. **Answers must be VERIFIABLE via direct string comparison**\n   - If the answer can be re-written in many formats, clearly specify the output format in the QUESTION\n   - Examples: \"Use YYYY/MM/DD.\", \"Respond True or False.\", \"Answer A, B, C, or D and nothing else.\"\n   - Answer should be a single VERIFIABLE value such as:\n     - User ID, user name, display name, first name, last name\n     - Channel ID, channel name\n     - Message ID, string\n     - URL, title\n     - Numerical quantity\n     - Timestamp, datetime\n     - Boolean (for True/False questions)\n     - Email address, phone number\n     - File ID, file name, file extension\n     - Multiple choice answer\n   - Answers must not require special formatting or complex, structured output\n   - Answer will be verified using DIRECT STRING COMPARISON\n\n### Readability\n\n2. **Answers should generally prefer HUMAN-READABLE formats**\n   - Examples: names, first name, last name, datetime, file name, message string, URL, yes/no, true/false, a/b/c/d\n   - Rather than opaque IDs (though IDs are acceptable)\n   - The VAST MAJORITY of answers should be human-readable\n\n### Stability\n\n3. **Answers must be STABLE/STATIONARY**\n   - Look at old content (e.g., conversations that have ended, projects that have launched, questions answered)\n   - Create QUESTIONS based on \"closed\" concepts that will always return the same answer\n   - Questions may ask to consider a fixed time window to insulate from non-stationary answers\n   - Rely on context UNLIKELY to change\n   - Example: if finding a paper name, be SPECIFIC enough so answer is not confused with papers published later\n\n4. **Answers must be CLEAR and UNAMBIGUOUS**\n   - Questions must be designed so there is a single, clear answer\n   - Answer can be derived from using the MCP server tools\n\n### Diversity\n\n5. **Answers must be DIVERSE**\n   - Answer should be a single VERIFIABLE value in diverse modalities and formats\n   - User concept: user ID, user name, display name, first name, last name, email address, phone number\n   - Channel concept: channel ID, channel name, channel topic\n   - Message concept: message ID, message string, timestamp, month, day, year\n\n6. **Answers must NOT be complex structures**\n   - Not a list of values\n   - Not a complex object\n   - Not a list of IDs or strings\n   - Not natural language text\n   - UNLESS the answer can be straightforwardly verified using DIRECT STRING COMPARISON\n   - And can be realistically reproduced\n   - It should be unlikely that an LLM would return the same list in any other order or format\n\n## Evaluation Process\n\n### Step 1: Documentation Inspection\n\nRead the documentation of the target API to understand:\n- Available endpoints and functionality\n- If ambiguity exists, fetch additional information from the web\n- Parallelize this step AS MUCH AS POSSIBLE\n- Ensure each subagent is ONLY examining documentation from the file system or on the web\n\n### Step 2: Tool Inspection\n\nList the tools available in the MCP server:\n- Inspect the MCP server directly\n- Understand input/output schemas, docstrings, and descriptions\n- WITHOUT calling the tools themselves at this stage\n\n### Step 3: Developing Understanding\n\nRepeat steps 1 \u0026 2 until you have a good understanding:\n- Iterate multiple times\n- Think about the kinds of tasks you want to create\n- Refine your understanding\n- At NO stage should you READ the code of the MCP server implementation itself\n- Use your intuition and understanding to create reasonable, realistic, but VERY challenging tasks\n\n### Step 4: Read-Only Content Inspection\n\nAfter understanding the API and tools, USE the MCP server tools:\n- Inspect content using READ-ONLY and NON-DESTRUCTIVE operations ONLY\n- Goal: identify specific content (e.g., users, channels, messages, projects, tasks) for creating realistic questions\n- Should NOT call any tools that modify state\n- Will NOT read the code of the MCP server implementation itself\n- Parallelize this step with individual sub-agents pursuing independent explorations\n- Ensure each subagent is only performing READ-ONLY, NON-DESTRUCTIVE, and IDEMPOTENT operations\n- BE CAREFUL: SOME TOOLS may return LOTS OF DATA which would cause you to run out of CONTEXT\n- Make INCREMENTAL, SMALL, AND TARGETED tool calls for exploration\n- In all tool call requests, use the `limit` parameter to limit results (\u003c10)\n- Use pagination\n\n### Step 5: Task Generation\n\nAfter inspecting the content, create 10 human-readable questions:\n- An LLM should be able to answer these with the MCP server\n- Follow all question and answer guidelines above\n\n## Output Format\n\nEach QA pair consists of a question and an answer. The output should be an XML file with this structure:\n\n```xml\n\u003cevaluation\u003e\n   \u003cqa_pair\u003e\n      \u003cquestion\u003eFind the project created in Q2 2024 with the highest number of completed tasks. What is the project name?\u003c/question\u003e\n      \u003canswer\u003eWebsite Redesign\u003c/answer\u003e\n   \u003c/qa_pair\u003e\n   \u003cqa_pair\u003e\n      \u003cquestion\u003eSearch for issues labeled as \"bug\" that were closed in March 2024. Which user closed the most issues? Provide their username.\u003c/question\u003e\n      \u003canswer\u003esarah_dev\u003c/answer\u003e\n   \u003c/qa_pair\u003e\n   \u003cqa_pair\u003e\n      \u003cquestion\u003eLook for pull requests that modified files in the /api directory and were merged between January 1 and January 31, 2024. How many different contributors worked on these PRs?\u003c/question\u003e\n      \u003canswer\u003e7\u003c/answer\u003e\n   \u003c/qa_pair\u003e\n   \u003cqa_pair\u003e\n      \u003cquestion\u003eFind the repository with the most stars that was created before 2023. What is the repository name?\u003c/question\u003e\n      \u003canswer\u003edata-pipeline\u003c/answer\u003e\n   \u003c/qa_pair\u003e\n\u003c/evaluation\u003e\n```\n\n## Evaluation Examples\n\n### Good Questions\n\n**Example 1: Multi-hop question requiring deep exploration (GitHub MCP)**\n```xml\n\u003cqa_pair\u003e\n   \u003cquestion\u003eFind the repository that was archived in Q3 2023 and had previously been the most forked project in the organization. What was the primary programming language used in that repository?\u003c/question\u003e\n   \u003canswer\u003ePython\u003c/answer\u003e\n\u003c/qa_pair\u003e\n```\n\nThis question is good because:\n- Requires multiple searches to find archived repositories\n- Needs to identify which had the most forks before archival\n- Requires examining repository details for the language\n- Answer is a simple, verifiable value\n- Based on historical (closed) data that won't change\n\n**Example 2: Requires understanding context without keyword matching (Project Management MCP)**\n```xml\n\u003cqa_pair\u003e\n   \u003cquestion\u003eLocate the initiative focused on improving customer onboarding that was completed in late 2023. The project lead created a retrospective document after completion. What was the lead's role title at that time?\u003c/question\u003e\n   \u003canswer\u003eProduct Manager\u003c/answer\u003e\n\u003c/qa_pair\u003e\n```\n\nThis question is good because:\n- Doesn't use specific project name (\"initiative focused on improving customer onboarding\")\n- Requires finding completed projects from specific timeframe\n- Needs to identify the project lead and their role\n- Requires understanding context from retrospective documents\n- Answer is human-readable and stable\n- Based on completed work (won't change)\n\n**Example 3: Complex aggregation requiring multiple steps (Issue Tracker MCP)**\n```xml\n\u003cqa_pair\u003e\n   \u003cquestion\u003eAmong all bugs reported in January 2024 that were marked as critical priority, which assignee resolved the highest percentage of their assigned bugs within 48 hours? Provide the assignee's username.\u003c/question\u003e\n   \u003canswer\u003ealex_eng\u003c/answer\u003e\n\u003c/qa_pair\u003e\n```\n\nThis question is good because:\n- Requires filtering bugs by date, priority, and status\n- Needs to group by assignee and calculate resolution rates\n- Requires understanding timestamps to determine 48-hour windows\n- Tests pagination (potentially many bugs to process)\n- Answer is a single username\n- Based on historical data from specific time period\n\n**Example 4: Requires synthesis across multiple data types (CRM MCP)**\n```xml\n\u003cqa_pair\u003e\n   \u003cquestion\u003eFind the account that upgraded from the Starter to Enterprise plan in Q4 2023 and had the highest annual contract value. What industry does this account operate in?\u003c/question\u003e\n   \u003canswer\u003eHealthcare\u003c/answer\u003e\n\u003c/qa_pair\u003e\n```\n\nThis question is good because:\n- Requires understanding subscription tier changes\n- Needs to identify upgrade events in specific timeframe\n- Requires comparing contract values\n- Must access account industry information\n- Answer is simple and verifiable\n- Based on completed historical transactions\n\n### Poor Questions\n\n**Example 1: Answer changes over time**\n```xml\n\u003cqa_pair\u003e\n   \u003cquestion\u003eHow many open issues are currently assigned to the engineering team?\u003c/question\u003e\n   \u003canswer\u003e47\u003c/answer\u003e\n\u003c/qa_pair\u003e\n```\n\nThis question is poor because:\n- The answer will change as issues are created, closed, or reassigned\n- Not based on stable/stationary data\n- Relies on \"current state\" which is dynamic\n\n**Example 2: Too easy with keyword search**\n```xml\n\u003cqa_pair\u003e\n   \u003cquestion\u003eFind the pull request with title \"Add authentication feature\" and tell me who created it.\u003c/question\u003e\n   \u003canswer\u003edeveloper123\u003c/answer\u003e\n\u003c/qa_pair\u003e\n```\n\nThis question is poor because:\n- Can be solved with a straightforward keyword search for exact title\n- Doesn't require deep exploration or understanding\n- No synthesis or analysis needed\n\n**Example 3: Ambiguous answer format**\n```xml\n\u003cqa_pair\u003e\n   \u003cquestion\u003eList all the repositories that have Python as their primary language.\u003c/question\u003e\n   \u003canswer\u003erepo1, repo2, repo3, data-pipeline, ml-tools\u003c/answer\u003e\n\u003c/qa_pair\u003e\n```\n\nThis question is poor because:\n- Answer is a list that could be returned in any order\n- Difficult to verify with direct string comparison\n- LLM might format differently (JSON array, comma-separated, newline-separated)\n- Better to ask for a specific aggregate (count) or superlative (most stars)\n\n## Verification Process\n\nAfter creating evaluations:\n\n1. **Examine the XML file** to understand the schema\n2. **Load each task instruction** and in parallel using the MCP server and tools, identify the correct answer by attempting to solve the task YOURSELF\n3. **Flag any operations** that require WRITE or DESTRUCTIVE operations\n4. **Accumulate all CORRECT answers** and replace any incorrect answers in the document\n5. **Remove any `\u003cqa_pair\u003e`** that require WRITE or DESTRUCTIVE operations\n\nRemember to parallelize solving tasks to avoid running out of context, then accumulate all answers and make changes to the file at the end.\n\n## Tips for Creating Quality Evaluations\n\n1. **Think Hard and Plan Ahead** before generating tasks\n2. **Parallelize Where Opportunity Arises** to speed up the process and manage context\n3. **Focus on Realistic Use Cases** that humans would actually want to accomplish\n4. **Create Challenging Questions** that test the limits of the MCP server's capabilities\n5. **Ensure Stability** by using historical data and closed concepts\n6. **Verify Answers** by solving the questions yourself using the MCP server tools\n7. **Iterate and Refine** based on what you learn during the process\n\n---\n\n# Running Evaluations\n\nAfter creating your evaluation file, you can use the provided evaluation harness to test your MCP server.\n\n## Setup\n\n1. **Install Dependencies**\n\n   ```bash\n   pip install -r scripts/requirements.txt\n   ```\n\n   Or install manually:\n   ```bash\n   pip install anthropic mcp\n   ```\n\n2. **Set API Key**\n\n   ```bash\n   export ANTHROPIC_API_KEY=your_api_key_here\n   ```\n\n## Evaluation File Format\n\nEvaluation files use XML format with `\u003cqa_pair\u003e` elements:\n\n```xml\n\u003cevaluation\u003e\n   \u003cqa_pair\u003e\n      \u003cquestion\u003eFind the project created in Q2 2024 with the highest number of completed tasks. What is the project name?\u003c/question\u003e\n      \u003canswer\u003eWebsite Redesign\u003c/answer\u003e\n   \u003c/qa_pair\u003e\n   \u003cqa_pair\u003e\n      \u003cquestion\u003eSearch for issues labeled as \"bug\" that were closed in March 2024. Which user closed the most issues? Provide their username.\u003c/question\u003e\n      \u003canswer\u003esarah_dev\u003c/answer\u003e\n   \u003c/qa_pair\u003e\n\u003c/evaluation\u003e\n```\n\n## Running Evaluations\n\nThe evaluation script (`scripts/evaluation.py`) supports three transport types:\n\n**Important:**\n- **stdio transport**: The evaluation script automatically launches and manages the MCP server process for you. Do not run the server manually.\n- **sse/http transports**: You must start the MCP server separately before running the evaluation. The script connects to the already-running server at the specified URL.\n\n### 1. Local STDIO Server\n\nFor locally-run MCP servers (script launches the server automatically):\n\n```bash\npython scripts/evaluation.py \\\n  -t stdio \\\n  -c python \\\n  -a my_mcp_server.py \\\n  evaluation.xml\n```\n\nWith environment variables:\n```bash\npython scripts/evaluation.py \\\n  -t stdio \\\n  -c python \\\n  -a my_mcp_server.py \\\n  -e API_KEY=abc123 \\\n  -e DEBUG=true \\\n  evaluation.xml\n```\n\n### 2. Server-Sent Events (SSE)\n\nFor SSE-based MCP servers (you must start the server first):\n\n```bash\npython scripts/evaluation.py \\\n  -t sse \\\n  -u https://example.com/mcp \\\n  -H \"Authorization: Bearer token123\" \\\n  -H \"X-Custom-Header: value\" \\\n  evaluation.xml\n```\n\n### 3. HTTP (Streamable HTTP)\n\nFor HTTP-based MCP servers (you must start the server first):\n\n```bash\npython scripts/evaluation.py \\\n  -t http \\\n  -u https://example.com/mcp \\\n  -H \"Authorization: Bearer token123\" \\\n  evaluation.xml\n```\n\n## Command-Line Options\n\n```\nusage: evaluation.py [-h] [-t {stdio,sse,http}] [-m MODEL] [-c COMMAND]\n                     [-a ARGS [ARGS ...]] [-e ENV [ENV ...]] [-u URL]\n                     [-H HEADERS [HEADERS ...]] [-o OUTPUT]\n                     eval_file\n\npositional arguments:\n  eval_file             Path to evaluation XML file\n\noptional arguments:\n  -h, --help            Show help message\n  -t, --transport       Transport type: stdio, sse, or http (default: stdio)\n  -m, --model           Claude model to use (default: claude-3-7-sonnet-20250219)\n  -o, --output          Output file for report (default: print to stdout)\n\nstdio options:\n  -c, --command         Command to run MCP server (e.g., python, node)\n  -a, --args            Arguments for the command (e.g., server.py)\n  -e, --env             Environment variables in KEY=VALUE format\n\nsse/http options:\n  -u, --url             MCP server URL\n  -H, --header          HTTP headers in 'Key: Value' format\n```\n\n## Output\n\nThe evaluation script generates a detailed report including:\n\n- **Summary Statistics**:\n  - Accuracy (correct/total)\n  - Average task duration\n  - Average tool calls per task\n  - Total tool calls\n\n- **Per-Task Results**:\n  - Prompt and expected response\n  - Actual response from the agent\n  - Whether the answer was correct (✅/❌)\n  - Duration and tool call details\n  - Agent's summary of its approach\n  - Agent's feedback on the tools\n\n### Save Report to File\n\n```bash\npython scripts/evaluation.py \\\n  -t stdio \\\n  -c python \\\n  -a my_server.py \\\n  -o evaluation_report.md \\\n  evaluation.xml\n```\n\n## Complete Example Workflow\n\nHere's a complete example of creating and running an evaluation:\n\n1. **Create your evaluation file** (`my_evaluation.xml`):\n\n```xml\n\u003cevaluation\u003e\n   \u003cqa_pair\u003e\n      \u003cquestion\u003eFind the user who created the most issues in January 2024. What is their username?\u003c/question\u003e\n      \u003canswer\u003ealice_developer\u003c/answer\u003e\n   \u003c/qa_pair\u003e\n   \u003cqa_pair\u003e\n      \u003cquestion\u003eAmong all pull requests merged in Q1 2024, which repository had the highest number? Provide the repository name.\u003c/question\u003e\n      \u003canswer\u003ebackend-api\u003c/answer\u003e\n   \u003c/qa_pair\u003e\n   \u003cqa_pair\u003e\n      \u003cquestion\u003eFind the project that was completed in December 2023 and had the longest duration from start to finish. How many days did it take?\u003c/question\u003e\n      \u003canswer\u003e127\u003c/answer\u003e\n   \u003c/qa_pair\u003e\n\u003c/evaluation\u003e\n```\n\n2. **Install dependencies**:\n\n```bash\npip install -r scripts/requirements.txt\nexport ANTHROPIC_API_KEY=your_api_key\n```\n\n3. **Run evaluation**:\n\n```bash\npython scripts/evaluation.py \\\n  -t stdio \\\n  -c python \\\n  -a github_mcp_server.py \\\n  -e GITHUB_TOKEN=ghp_xxx \\\n  -o github_eval_report.md \\\n  my_evaluation.xml\n```\n\n4. **Review the report** in `github_eval_report.md` to:\n   - See which questions passed/failed\n   - Read the agent's feedback on your tools\n   - Identify areas for improvement\n   - Iterate on your MCP server design\n\n## Troubleshooting\n\n### Connection Errors\n\nIf you get connection errors:\n- **STDIO**: Verify the command and arguments are correct\n- **SSE/HTTP**: Check the URL is accessible and headers are correct\n- Ensure any required API keys are set in environment variables or headers\n\n### Low Accuracy\n\nIf many evaluations fail:\n- Review the agent's feedback for each task\n- Check if tool descriptions are clear and comprehensive\n- Verify input parameters are well-documented\n- Consider whether tools return too much or too little data\n- Ensure error messages are actionable\n\n### Timeout Issues\n\nIf tasks are timing out:\n- Use a more capable model (e.g., `claude-3-7-sonnet-20250219`)\n- Check if tools are returning too much data\n- Verify pagination is working correctly\n- Consider simplifying complex questions","reference/mcp_best_practices.md":"# MCP Server Best Practices\n\n## Quick Reference\n\n### Server Naming\n- **Python**: `{service}_mcp` (e.g., `slack_mcp`)\n- **Node/TypeScript**: `{service}-mcp-server` (e.g., `slack-mcp-server`)\n\n### Tool Naming\n- Use snake_case with service prefix\n- Format: `{service}_{action}_{resource}`\n- Example: `slack_send_message`, `github_create_issue`\n\n### Response Formats\n- Support both JSON and Markdown formats\n- JSON for programmatic processing\n- Markdown for human readability\n\n### Pagination\n- Always respect `limit` parameter\n- Return `has_more`, `next_offset`, `total_count`\n- Default to 20-50 items\n\n### Transport\n- **Streamable HTTP**: For remote servers, multi-client scenarios\n- **stdio**: For local integrations, command-line tools\n- Avoid SSE (deprecated in favor of streamable HTTP)\n\n---\n\n## Server Naming Conventions\n\nFollow these standardized naming patterns:\n\n**Python**: Use format `{service}_mcp` (lowercase with underscores)\n- Examples: `slack_mcp`, `github_mcp`, `jira_mcp`\n\n**Node/TypeScript**: Use format `{service}-mcp-server` (lowercase with hyphens)\n- Examples: `slack-mcp-server`, `github-mcp-server`, `jira-mcp-server`\n\nThe name should be general, descriptive of the service being integrated, easy to infer from the task description, and without version numbers.\n\n---\n\n## Tool Naming and Design\n\n### Tool Naming\n\n1. **Use snake_case**: `search_users`, `create_project`, `get_channel_info`\n2. **Include service prefix**: Anticipate that your MCP server may be used alongside other MCP servers\n   - Use `slack_send_message` instead of just `send_message`\n   - Use `github_create_issue` instead of just `create_issue`\n3. **Be action-oriented**: Start with verbs (get, list, search, create, etc.)\n4. **Be specific**: Avoid generic names that could conflict with other servers\n\n### Tool Design\n\n- Tool descriptions must narrowly and unambiguously describe functionality\n- Descriptions must precisely match actual functionality\n- Provide tool annotations (readOnlyHint, destructiveHint, idempotentHint, openWorldHint)\n- Keep tool operations focused and atomic\n\n---\n\n## Response Formats\n\nAll tools that return data should support multiple formats:\n\n### JSON Format (`response_format=\"json\"`)\n- Machine-readable structured data\n- Include all available fields and metadata\n- Consistent field names and types\n- Use for programmatic processing\n\n### Markdown Format (`response_format=\"markdown\"`, typically default)\n- Human-readable formatted text\n- Use headers, lists, and formatting for clarity\n- Convert timestamps to human-readable format\n- Show display names with IDs in parentheses\n- Omit verbose metadata\n\n---\n\n## Pagination\n\nFor tools that list resources:\n\n- **Always respect the `limit` parameter**\n- **Implement pagination**: Use `offset` or cursor-based pagination\n- **Return pagination metadata**: Include `has_more`, `next_offset`/`next_cursor`, `total_count`\n- **Never load all results into memory**: Especially important for large datasets\n- **Default to reasonable limits**: 20-50 items is typical\n\nExample pagination response:\n```json\n{\n  \"total\": 150,\n  \"count\": 20,\n  \"offset\": 0,\n  \"items\": [...],\n  \"has_more\": true,\n  \"next_offset\": 20\n}\n```\n\n---\n\n## Transport Options\n\n### Streamable HTTP\n\n**Best for**: Remote servers, web services, multi-client scenarios\n\n**Characteristics**:\n- Bidirectional communication over HTTP\n- Supports multiple simultaneous clients\n- Can be deployed as a web service\n- Enables server-to-client notifications\n\n**Use when**:\n- Serving multiple clients simultaneously\n- Deploying as a cloud service\n- Integration with web applications\n\n### stdio\n\n**Best for**: Local integrations, command-line tools\n\n**Characteristics**:\n- Standard input/output stream communication\n- Simple setup, no network configuration needed\n- Runs as a subprocess of the client\n\n**Use when**:\n- Building tools for local development environments\n- Integrating with desktop applications\n- Single-user, single-session scenarios\n\n**Note**: stdio servers should NOT log to stdout (use stderr for logging)\n\n### Transport Selection\n\n| Criterion | stdio | Streamable HTTP |\n|-----------|-------|-----------------|\n| **Deployment** | Local | Remote |\n| **Clients** | Single | Multiple |\n| **Complexity** | Low | Medium |\n| **Real-time** | No | Yes |\n\n---\n\n## Security Best Practices\n\n### Authentication and Authorization\n\n**OAuth 2.1**:\n- Use secure OAuth 2.1 with certificates from recognized authorities\n- Validate access tokens before processing requests\n- Only accept tokens specifically intended for your server\n\n**API Keys**:\n- Store API keys in environment variables, never in code\n- Validate keys on server startup\n- Provide clear error messages when authentication fails\n\n### Input Validation\n\n- Sanitize file paths to prevent directory traversal\n- Validate URLs and external identifiers\n- Check parameter sizes and ranges\n- Prevent command injection in system calls\n- Use schema validation (Pydantic/Zod) for all inputs\n\n### Error Handling\n\n- Don't expose internal errors to clients\n- Log security-relevant errors server-side\n- Provide helpful but not revealing error messages\n- Clean up resources after errors\n\n### DNS Rebinding Protection\n\nFor streamable HTTP servers running locally:\n- Enable DNS rebinding protection\n- Validate the `Origin` header on all incoming connections\n- Bind to `127.0.0.1` rather than `0.0.0.0`\n\n---\n\n## Tool Annotations\n\nProvide annotations to help clients understand tool behavior:\n\n| Annotation | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `readOnlyHint` | boolean | false | Tool does not modify its environment |\n| `destructiveHint` | boolean | true | Tool may perform destructive updates |\n| `idempotentHint` | boolean | false | Repeated calls with same args have no additional effect |\n| `openWorldHint` | boolean | true | Tool interacts with external entities |\n\n**Important**: Annotations are hints, not security guarantees. Clients should not make security-critical decisions based solely on annotations.\n\n---\n\n## Error Handling\n\n- Use standard JSON-RPC error codes\n- Report tool errors within result objects (not protocol-level errors)\n- Provide helpful, specific error messages with suggested next steps\n- Don't expose internal implementation details\n- Clean up resources properly on errors\n\nExample error handling:\n```typescript\ntry {\n  const result = performOperation();\n  return { content: [{ type: \"text\", text: result }] };\n} catch (error) {\n  return {\n    isError: true,\n    content: [{\n      type: \"text\",\n      text: `Error: ${error.message}. Try using filter='active_only' to reduce results.`\n    }]\n  };\n}\n```\n\n---\n\n## Testing Requirements\n\nComprehensive testing should cover:\n\n- **Functional testing**: Verify correct execution with valid/invalid inputs\n- **Integration testing**: Test interaction with external systems\n- **Security testing**: Validate auth, input sanitization, rate limiting\n- **Performance testing**: Check behavior under load, timeouts\n- **Error handling**: Ensure proper error reporting and cleanup\n\n---\n\n## Documentation Requirements\n\n- Provide clear documentation of all tools and capabilities\n- Include working examples (at least 3 per major feature)\n- Document security considerations\n- Specify required permissions and access levels\n- Document rate limits and performance characteristics\n","reference/node_mcp_server.md":"# Node/TypeScript MCP Server Implementation Guide\n\n## Overview\n\nThis document provides Node/TypeScript-specific best practices and examples for implementing MCP servers using the MCP TypeScript SDK. It covers project structure, server setup, tool registration patterns, input validation with Zod, error handling, and complete working examples.\n\n---\n\n## Quick Reference\n\n### Key Imports\n```typescript\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/streamableHttp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport express from \"express\";\nimport { z } from \"zod\";\n```\n\n### Server Initialization\n```typescript\nconst server = new McpServer({\n  name: \"service-mcp-server\",\n  version: \"1.0.0\"\n});\n```\n\n### Tool Registration Pattern\n```typescript\nserver.registerTool(\n  \"tool_name\",\n  {\n    title: \"Tool Display Name\",\n    description: \"What the tool does\",\n    inputSchema: { param: z.string() },\n    outputSchema: { result: z.string() }\n  },\n  async ({ param }) =\u003e {\n    const output = { result: `Processed: ${param}` };\n    return {\n      content: [{ type: \"text\", text: JSON.stringify(output) }],\n      structuredContent: output // Modern pattern for structured data\n    };\n  }\n);\n```\n\n---\n\n## MCP TypeScript SDK\n\nThe official MCP TypeScript SDK provides:\n- `McpServer` class for server initialization\n- `registerTool` method for tool registration\n- Zod schema integration for runtime input validation\n- Type-safe tool handler implementations\n\n**IMPORTANT - Use Modern APIs Only:**\n- **DO use**: `server.registerTool()`, `server.registerResource()`, `server.registerPrompt()`\n- **DO NOT use**: Old deprecated APIs such as `server.tool()`, `server.setRequestHandler(ListToolsRequestSchema, ...)`, or manual handler registration\n- The `register*` methods provide better type safety, automatic schema handling, and are the recommended approach\n\nSee the MCP SDK documentation in the references for complete details.\n\n## Server Naming Convention\n\nNode/TypeScript MCP servers must follow this naming pattern:\n- **Format**: `{service}-mcp-server` (lowercase with hyphens)\n- **Examples**: `github-mcp-server`, `jira-mcp-server`, `stripe-mcp-server`\n\nThe name should be:\n- General (not tied to specific features)\n- Descriptive of the service/API being integrated\n- Easy to infer from the task description\n- Without version numbers or dates\n\n## Project Structure\n\nCreate the following structure for Node/TypeScript MCP servers:\n\n```\n{service}-mcp-server/\n├── package.json\n├── tsconfig.json\n├── README.md\n├── src/\n│   ├── index.ts          # Main entry point with McpServer initialization\n│   ├── types.ts          # TypeScript type definitions and interfaces\n│   ├── tools/            # Tool implementations (one file per domain)\n│   ├── services/         # API clients and shared utilities\n│   ├── schemas/          # Zod validation schemas\n│   └── constants.ts      # Shared constants (API_URL, CHARACTER_LIMIT, etc.)\n└── dist/                 # Built JavaScript files (entry point: dist/index.js)\n```\n\n## Tool Implementation\n\n### Tool Naming\n\nUse snake_case for tool names (e.g., \"search_users\", \"create_project\", \"get_channel_info\") with clear, action-oriented names.\n\n**Avoid Naming Conflicts**: Include the service context to prevent overlaps:\n- Use \"slack_send_message\" instead of just \"send_message\"\n- Use \"github_create_issue\" instead of just \"create_issue\"\n- Use \"asana_list_tasks\" instead of just \"list_tasks\"\n\n### Tool Structure\n\nTools are registered using the `registerTool` method with the following requirements:\n- Use Zod schemas for runtime input validation and type safety\n- The `description` field must be explicitly provided - JSDoc comments are NOT automatically extracted\n- Explicitly provide `title`, `description`, `inputSchema`, and `annotations`\n- The `inputSchema` must be a Zod schema object (not a JSON schema)\n- Type all parameters and return values explicitly\n\n```typescript\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\n\nconst server = new McpServer({\n  name: \"example-mcp\",\n  version: \"1.0.0\"\n});\n\n// Zod schema for input validation\nconst UserSearchInputSchema = z.object({\n  query: z.string()\n    .min(2, \"Query must be at least 2 characters\")\n    .max(200, \"Query must not exceed 200 characters\")\n    .describe(\"Search string to match against names/emails\"),\n  limit: z.number()\n    .int()\n    .min(1)\n    .max(100)\n    .default(20)\n    .describe(\"Maximum results to return\"),\n  offset: z.number()\n    .int()\n    .min(0)\n    .default(0)\n    .describe(\"Number of results to skip for pagination\"),\n  response_format: z.nativeEnum(ResponseFormat)\n    .default(ResponseFormat.MARKDOWN)\n    .describe(\"Output format: 'markdown' for human-readable or 'json' for machine-readable\")\n}).strict();\n\n// Type definition from Zod schema\ntype UserSearchInput = z.infer\u003ctypeof UserSearchInputSchema\u003e;\n\nserver.registerTool(\n  \"example_search_users\",\n  {\n    title: \"Search Example Users\",\n    description: `Search for users in the Example system by name, email, or team.\n\nThis tool searches across all user profiles in the Example platform, supporting partial matches and various search filters. It does NOT create or modify users, only searches existing ones.\n\nArgs:\n  - query (string): Search string to match against names/emails\n  - limit (number): Maximum results to return, between 1-100 (default: 20)\n  - offset (number): Number of results to skip for pagination (default: 0)\n  - response_format ('markdown' | 'json'): Output format (default: 'markdown')\n\nReturns:\n  For JSON format: Structured data with schema:\n  {\n    \"total\": number,           // Total number of matches found\n    \"count\": number,           // Number of results in this response\n    \"offset\": number,          // Current pagination offset\n    \"users\": [\n      {\n        \"id\": string,          // User ID (e.g., \"U123456789\")\n        \"name\": string,        // Full name (e.g., \"John Doe\")\n        \"email\": string,       // Email address\n        \"team\": string,        // Team name (optional)\n        \"active\": boolean      // Whether user is active\n      }\n    ],\n    \"has_more\": boolean,       // Whether more results are available\n    \"next_offset\": number      // Offset for next page (if has_more is true)\n  }\n\nExamples:\n  - Use when: \"Find all marketing team members\" -\u003e params with query=\"team:marketing\"\n  - Use when: \"Search for John's account\" -\u003e params with query=\"john\"\n  - Don't use when: You need to create a user (use example_create_user instead)\n\nError Handling:\n  - Returns \"Error: Rate limit exceeded\" if too many requests (429 status)\n  - Returns \"No users found matching '\u003cquery\u003e'\" if search returns empty`,\n    inputSchema: UserSearchInputSchema,\n    annotations: {\n      readOnlyHint: true,\n      destructiveHint: false,\n      idempotentHint: true,\n      openWorldHint: true\n    }\n  },\n  async (params: UserSearchInput) =\u003e {\n    try {\n      // Input validation is handled by Zod schema\n      // Make API request using validated parameters\n      const data = await makeApiRequest\u003cany\u003e(\n        \"users/search\",\n        \"GET\",\n        undefined,\n        {\n          q: params.query,\n          limit: params.limit,\n          offset: params.offset\n        }\n      );\n\n      const users = data.users || [];\n      const total = data.total || 0;\n\n      if (!users.length) {\n        return {\n          content: [{\n            type: \"text\",\n            text: `No users found matching '${params.query}'`\n          }]\n        };\n      }\n\n      // Prepare structured output\n      const output = {\n        total,\n        count: users.length,\n        offset: params.offset,\n        users: users.map((user: any) =\u003e ({\n          id: user.id,\n          name: user.name,\n          email: user.email,\n          ...(user.team ? { team: user.team } : {}),\n          active: user.active ?? true\n        })),\n        has_more: total \u003e params.offset + users.length,\n        ...(total \u003e params.offset + users.length ? {\n          next_offset: params.offset + users.length\n        } : {})\n      };\n\n      // Format text representation based on requested format\n      let textContent: string;\n      if (params.response_format === ResponseFormat.MARKDOWN) {\n        const lines = [`# User Search Results: '${params.query}'`, \"\",\n          `Found ${total} users (showing ${users.length})`, \"\"];\n        for (const user of users) {\n          lines.push(`## ${user.name} (${user.id})`);\n          lines.push(`- **Email**: ${user.email}`);\n          if (user.team) lines.push(`- **Team**: ${user.team}`);\n          lines.push(\"\");\n        }\n        textContent = lines.join(\"\\n\");\n      } else {\n        textContent = JSON.stringify(output, null, 2);\n      }\n\n      return {\n        content: [{ type: \"text\", text: textContent }],\n        structuredContent: output // Modern pattern for structured data\n      };\n    } catch (error) {\n      return {\n        content: [{\n          type: \"text\",\n          text: handleApiError(error)\n        }]\n      };\n    }\n  }\n);\n```\n\n## Zod Schemas for Input Validation\n\nZod provides runtime type validation:\n\n```typescript\nimport { z } from \"zod\";\n\n// Basic schema with validation\nconst CreateUserSchema = z.object({\n  name: z.string()\n    .min(1, \"Name is required\")\n    .max(100, \"Name must not exceed 100 characters\"),\n  email: z.string()\n    .email(\"Invalid email format\"),\n  age: z.number()\n    .int(\"Age must be a whole number\")\n    .min(0, \"Age cannot be negative\")\n    .max(150, \"Age cannot be greater than 150\")\n}).strict();  // Use .strict() to forbid extra fields\n\n// Enums\nenum ResponseFormat {\n  MARKDOWN = \"markdown\",\n  JSON = \"json\"\n}\n\nconst SearchSchema = z.object({\n  response_format: z.nativeEnum(ResponseFormat)\n    .default(ResponseFormat.MARKDOWN)\n    .describe(\"Output format\")\n});\n\n// Optional fields with defaults\nconst PaginationSchema = z.object({\n  limit: z.number()\n    .int()\n    .min(1)\n    .max(100)\n    .default(20)\n    .describe(\"Maximum results to return\"),\n  offset: z.number()\n    .int()\n    .min(0)\n    .default(0)\n    .describe(\"Number of results to skip\")\n});\n```\n\n## Response Format Options\n\nSupport multiple output formats for flexibility:\n\n```typescript\nenum ResponseFormat {\n  MARKDOWN = \"markdown\",\n  JSON = \"json\"\n}\n\nconst inputSchema = z.object({\n  query: z.string(),\n  response_format: z.nativeEnum(ResponseFormat)\n    .default(ResponseFormat.MARKDOWN)\n    .describe(\"Output format: 'markdown' for human-readable or 'json' for machine-readable\")\n});\n```\n\n**Markdown format**:\n- Use headers, lists, and formatting for clarity\n- Convert timestamps to human-readable format\n- Show display names with IDs in parentheses\n- Omit verbose metadata\n- Group related information logically\n\n**JSON format**:\n- Return complete, structured data suitable for programmatic processing\n- Include all available fields and metadata\n- Use consistent field names and types\n\n## Pagination Implementation\n\nFor tools that list resources:\n\n```typescript\nconst ListSchema = z.object({\n  limit: z.number().int().min(1).max(100).default(20),\n  offset: z.number().int().min(0).default(0)\n});\n\nasync function listItems(params: z.infer\u003ctypeof ListSchema\u003e) {\n  const data = await apiRequest(params.limit, params.offset);\n\n  const response = {\n    total: data.total,\n    count: data.items.length,\n    offset: params.offset,\n    items: data.items,\n    has_more: data.total \u003e params.offset + data.items.length,\n    next_offset: data.total \u003e params.offset + data.items.length\n      ? params.offset + data.items.length\n      : undefined\n  };\n\n  return JSON.stringify(response, null, 2);\n}\n```\n\n## Character Limits and Truncation\n\nAdd a CHARACTER_LIMIT constant to prevent overwhelming responses:\n\n```typescript\n// At module level in constants.ts\nexport const CHARACTER_LIMIT = 25000;  // Maximum response size in characters\n\nasync function searchTool(params: SearchInput) {\n  let result = generateResponse(data);\n\n  // Check character limit and truncate if needed\n  if (result.length \u003e CHARACTER_LIMIT) {\n    const truncatedData = data.slice(0, Math.max(1, data.length / 2));\n    response.data = truncatedData;\n    response.truncated = true;\n    response.truncation_message =\n      `Response truncated from ${data.length} to ${truncatedData.length} items. ` +\n      `Use 'offset' parameter or add filters to see more results.`;\n    result = JSON.stringify(response, null, 2);\n  }\n\n  return result;\n}\n```\n\n## Error Handling\n\nProvide clear, actionable error messages:\n\n```typescript\nimport axios, { AxiosError } from \"axios\";\n\nfunction handleApiError(error: unknown): string {\n  if (error instanceof AxiosError) {\n    if (error.response) {\n      switch (error.response.status) {\n        case 404:\n          return \"Error: Resource not found. Please check the ID is correct.\";\n        case 403:\n          return \"Error: Permission denied. You don't have access to this resource.\";\n        case 429:\n          return \"Error: Rate limit exceeded. Please wait before making more requests.\";\n        default:\n          return `Error: API request failed with status ${error.response.status}`;\n      }\n    } else if (error.code === \"ECONNABORTED\") {\n      return \"Error: Request timed out. Please try again.\";\n    }\n  }\n  return `Error: Unexpected error occurred: ${error instanceof Error ? error.message : String(error)}`;\n}\n```\n\n## Shared Utilities\n\nExtract common functionality into reusable functions:\n\n```typescript\n// Shared API request function\nasync function makeApiRequest\u003cT\u003e(\n  endpoint: string,\n  method: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" = \"GET\",\n  data?: any,\n  params?: any\n): Promise\u003cT\u003e {\n  try {\n    const response = await axios({\n      method,\n      url: `${API_BASE_URL}/${endpoint}`,\n      data,\n      params,\n      timeout: 30000,\n      headers: {\n        \"Content-Type\": \"application/json\",\n        \"Accept\": \"application/json\"\n      }\n    });\n    return response.data;\n  } catch (error) {\n    throw error;\n  }\n}\n```\n\n## Async/Await Best Practices\n\nAlways use async/await for network requests and I/O operations:\n\n```typescript\n// Good: Async network request\nasync function fetchData(resourceId: string): Promise\u003cResourceData\u003e {\n  const response = await axios.get(`${API_URL}/resource/${resourceId}`);\n  return response.data;\n}\n\n// Bad: Promise chains\nfunction fetchData(resourceId: string): Promise\u003cResourceData\u003e {\n  return axios.get(`${API_URL}/resource/${resourceId}`)\n    .then(response =\u003e response.data);  // Harder to read and maintain\n}\n```\n\n## TypeScript Best Practices\n\n1. **Use Strict TypeScript**: Enable strict mode in tsconfig.json\n2. **Define Interfaces**: Create clear interface definitions for all data structures\n3. **Avoid `any`**: Use proper types or `unknown` instead of `any`\n4. **Zod for Runtime Validation**: Use Zod schemas to validate external data\n5. **Type Guards**: Create type guard functions for complex type checking\n6. **Error Handling**: Always use try-catch with proper error type checking\n7. **Null Safety**: Use optional chaining (`?.`) and nullish coalescing (`??`)\n\n```typescript\n// Good: Type-safe with Zod and interfaces\ninterface UserResponse {\n  id: string;\n  name: string;\n  email: string;\n  team?: string;\n  active: boolean;\n}\n\nconst UserSchema = z.object({\n  id: z.string(),\n  name: z.string(),\n  email: z.string().email(),\n  team: z.string().optional(),\n  active: z.boolean()\n});\n\ntype User = z.infer\u003ctypeof UserSchema\u003e;\n\nasync function getUser(id: string): Promise\u003cUser\u003e {\n  const data = await apiCall(`/users/${id}`);\n  return UserSchema.parse(data);  // Runtime validation\n}\n\n// Bad: Using any\nasync function getUser(id: string): Promise\u003cany\u003e {\n  return await apiCall(`/users/${id}`);  // No type safety\n}\n```\n\n## Package Configuration\n\n### package.json\n\n```json\n{\n  \"name\": \"{service}-mcp-server\",\n  \"version\": \"1.0.0\",\n  \"description\": \"MCP server for {Service} API integration\",\n  \"type\": \"module\",\n  \"main\": \"dist/index.js\",\n  \"scripts\": {\n    \"start\": \"node dist/index.js\",\n    \"dev\": \"tsx watch src/index.ts\",\n    \"build\": \"tsc\",\n    \"clean\": \"rm -rf dist\"\n  },\n  \"engines\": {\n    \"node\": \"\u003e=18\"\n  },\n  \"dependencies\": {\n    \"@modelcontextprotocol/sdk\": \"^1.6.1\",\n    \"axios\": \"^1.7.9\",\n    \"zod\": \"^3.23.8\"\n  },\n  \"devDependencies\": {\n    \"@types/node\": \"^22.10.0\",\n    \"tsx\": \"^4.19.2\",\n    \"typescript\": \"^5.7.2\"\n  }\n}\n```\n\n### tsconfig.json\n\n```json\n{\n  \"compilerOptions\": {\n    \"target\": \"ES2022\",\n    \"module\": \"Node16\",\n    \"moduleResolution\": \"Node16\",\n    \"lib\": [\"ES2022\"],\n    \"outDir\": \"./dist\",\n    \"rootDir\": \"./src\",\n    \"strict\": true,\n    \"esModuleInterop\": true,\n    \"skipLibCheck\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"declaration\": true,\n    \"declarationMap\": true,\n    \"sourceMap\": true,\n    \"allowSyntheticDefaultImports\": true\n  },\n  \"include\": [\"src/**/*\"],\n  \"exclude\": [\"node_modules\", \"dist\"]\n}\n```\n\n## Complete Example\n\n```typescript\n#!/usr/bin/env node\n/**\n * MCP Server for Example Service.\n *\n * This server provides tools to interact with Example API, including user search,\n * project management, and data export capabilities.\n */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { z } from \"zod\";\nimport axios, { AxiosError } from \"axios\";\n\n// Constants\nconst API_BASE_URL = \"https://api.example.com/v1\";\nconst CHARACTER_LIMIT = 25000;\n\n// Enums\nenum ResponseFormat {\n  MARKDOWN = \"markdown\",\n  JSON = \"json\"\n}\n\n// Zod schemas\nconst UserSearchInputSchema = z.object({\n  query: z.string()\n    .min(2, \"Query must be at least 2 characters\")\n    .max(200, \"Query must not exceed 200 characters\")\n    .describe(\"Search string to match against names/emails\"),\n  limit: z.number()\n    .int()\n    .min(1)\n    .max(100)\n    .default(20)\n    .describe(\"Maximum results to return\"),\n  offset: z.number()\n    .int()\n    .min(0)\n    .default(0)\n    .describe(\"Number of results to skip for pagination\"),\n  response_format: z.nativeEnum(ResponseFormat)\n    .default(ResponseFormat.MARKDOWN)\n    .describe(\"Output format: 'markdown' for human-readable or 'json' for machine-readable\")\n}).strict();\n\ntype UserSearchInput = z.infer\u003ctypeof UserSearchInputSchema\u003e;\n\n// Shared utility functions\nasync function makeApiRequest\u003cT\u003e(\n  endpoint: string,\n  method: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" = \"GET\",\n  data?: any,\n  params?: any\n): Promise\u003cT\u003e {\n  try {\n    const response = await axios({\n      method,\n      url: `${API_BASE_URL}/${endpoint}`,\n      data,\n      params,\n      timeout: 30000,\n      headers: {\n        \"Content-Type\": \"application/json\",\n        \"Accept\": \"application/json\"\n      }\n    });\n    return response.data;\n  } catch (error) {\n    throw error;\n  }\n}\n\nfunction handleApiError(error: unknown): string {\n  if (error instanceof AxiosError) {\n    if (error.response) {\n      switch (error.response.status) {\n        case 404:\n          return \"Error: Resource not found. Please check the ID is correct.\";\n        case 403:\n          return \"Error: Permission denied. You don't have access to this resource.\";\n        case 429:\n          return \"Error: Rate limit exceeded. Please wait before making more requests.\";\n        default:\n          return `Error: API request failed with status ${error.response.status}`;\n      }\n    } else if (error.code === \"ECONNABORTED\") {\n      return \"Error: Request timed out. Please try again.\";\n    }\n  }\n  return `Error: Unexpected error occurred: ${error instanceof Error ? error.message : String(error)}`;\n}\n\n// Create MCP server instance\nconst server = new McpServer({\n  name: \"example-mcp\",\n  version: \"1.0.0\"\n});\n\n// Register tools\nserver.registerTool(\n  \"example_search_users\",\n  {\n    title: \"Search Example Users\",\n    description: `[Full description as shown above]`,\n    inputSchema: UserSearchInputSchema,\n    annotations: {\n      readOnlyHint: true,\n      destructiveHint: false,\n      idempotentHint: true,\n      openWorldHint: true\n    }\n  },\n  async (params: UserSearchInput) =\u003e {\n    // Implementation as shown above\n  }\n);\n\n// Main function\n// For stdio (local):\nasync function runStdio() {\n  if (!process.env.EXAMPLE_API_KEY) {\n    console.error(\"ERROR: EXAMPLE_API_KEY environment variable is required\");\n    process.exit(1);\n  }\n\n  const transport = new StdioServerTransport();\n  await server.connect(transport);\n  console.error(\"MCP server running via stdio\");\n}\n\n// For streamable HTTP (remote):\nasync function runHTTP() {\n  if (!process.env.EXAMPLE_API_KEY) {\n    console.error(\"ERROR: EXAMPLE_API_KEY environment variable is required\");\n    process.exit(1);\n  }\n\n  const app = express();\n  app.use(express.json());\n\n  app.post('/mcp', async (req, res) =\u003e {\n    const transport = new StreamableHTTPServerTransport({\n      sessionIdGenerator: undefined,\n      enableJsonResponse: true\n    });\n    res.on('close', () =\u003e transport.close());\n    await server.connect(transport);\n    await transport.handleRequest(req, res, req.body);\n  });\n\n  const port = parseInt(process.env.PORT || '3000');\n  app.listen(port, () =\u003e {\n    console.error(`MCP server running on http://localhost:${port}/mcp`);\n  });\n}\n\n// Choose transport based on environment\nconst transport = process.env.TRANSPORT || 'stdio';\nif (transport === 'http') {\n  runHTTP().catch(error =\u003e {\n    console.error(\"Server error:\", error);\n    process.exit(1);\n  });\n} else {\n  runStdio().catch(error =\u003e {\n    console.error(\"Server error:\", error);\n    process.exit(1);\n  });\n}\n```\n\n---\n\n## Advanced MCP Features\n\n### Resource Registration\n\nExpose data as resources for efficient, URI-based access:\n\n```typescript\nimport { ResourceTemplate } from \"@modelcontextprotocol/sdk/types.js\";\n\n// Register a resource with URI template\nserver.registerResource(\n  {\n    uri: \"file://documents/{name}\",\n    name: \"Document Resource\",\n    description: \"Access documents by name\",\n    mimeType: \"text/plain\"\n  },\n  async (uri: string) =\u003e {\n    // Extract parameter from URI\n    const match = uri.match(/^file:\\/\\/documents\\/(.+)$/);\n    if (!match) {\n      throw new Error(\"Invalid URI format\");\n    }\n\n    const documentName = match[1];\n    const content = await loadDocument(documentName);\n\n    return {\n      contents: [{\n        uri,\n        mimeType: \"text/plain\",\n        text: content\n      }]\n    };\n  }\n);\n\n// List available resources dynamically\nserver.registerResourceList(async () =\u003e {\n  const documents = await getAvailableDocuments();\n  return {\n    resources: documents.map(doc =\u003e ({\n      uri: `file://documents/${doc.name}`,\n      name: doc.name,\n      mimeType: \"text/plain\",\n      description: doc.description\n    }))\n  };\n});\n```\n\n**When to use Resources vs Tools:**\n- **Resources**: For data access with simple URI-based parameters\n- **Tools**: For complex operations requiring validation and business logic\n- **Resources**: When data is relatively static or template-based\n- **Tools**: When operations have side effects or complex workflows\n\n### Transport Options\n\nThe TypeScript SDK supports two main transport mechanisms:\n\n#### Streamable HTTP (Recommended for Remote Servers)\n\n```typescript\nimport { StreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/streamableHttp.js\";\nimport express from \"express\";\n\nconst app = express();\napp.use(express.json());\n\napp.post('/mcp', async (req, res) =\u003e {\n  // Create new transport for each request (stateless, prevents request ID collisions)\n  const transport = new StreamableHTTPServerTransport({\n    sessionIdGenerator: undefined,\n    enableJsonResponse: true\n  });\n\n  res.on('close', () =\u003e transport.close());\n\n  await server.connect(transport);\n  await transport.handleRequest(req, res, req.body);\n});\n\napp.listen(3000);\n```\n\n#### stdio (For Local Integrations)\n\n```typescript\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\n\nconst transport = new StdioServerTransport();\nawait server.connect(transport);\n```\n\n**Transport selection:**\n- **Streamable HTTP**: Web services, remote access, multiple clients\n- **stdio**: Command-line tools, local development, subprocess integration\n\n### Notification Support\n\nNotify clients when server state changes:\n\n```typescript\n// Notify when tools list changes\nserver.notification({\n  method: \"notifications/tools/list_changed\"\n});\n\n// Notify when resources change\nserver.notification({\n  method: \"notifications/resources/list_changed\"\n});\n```\n\nUse notifications sparingly - only when server capabilities genuinely change.\n\n---\n\n## Code Best Practices\n\n### Code Composability and Reusability\n\nYour implementation MUST prioritize composability and code reuse:\n\n1. **Extract Common Functionality**:\n   - Create reusable helper functions for operations used across multiple tools\n   - Build shared API clients for HTTP requests instead of duplicating code\n   - Centralize error handling logic in utility functions\n   - Extract business logic into dedicated functions that can be composed\n   - Extract shared markdown or JSON field selection \u0026 formatting functionality\n\n2. **Avoid Duplication**:\n   - NEVER copy-paste similar code between tools\n   - If you find yourself writing similar logic twice, extract it into a function\n   - Common operations like pagination, filtering, field selection, and formatting should be shared\n   - Authentication/authorization logic should be centralized\n\n## Building and Running\n\nAlways build your TypeScript code before running:\n\n```bash\n# Build the project\nnpm run build\n\n# Run the server\nnpm start\n\n# Development with auto-reload\nnpm run dev\n```\n\nAlways ensure `npm run build` completes successfully before considering the implementation complete.\n\n## Quality Checklist\n\nBefore finalizing your Node/TypeScript MCP server implementation, ensure:\n\n### Strategic Design\n- [ ] Tools enable complete workflows, not just API endpoint wrappers\n- [ ] Tool names reflect natural task subdivisions\n- [ ] Response formats optimize for agent context efficiency\n- [ ] Human-readable identifiers used where appropriate\n- [ ] Error messages guide agents toward correct usage\n\n### Implementation Quality\n- [ ] FOCUSED IMPLEMENTATION: Most important and valuable tools implemented\n- [ ] All tools registered using `registerTool` with complete configuration\n- [ ] All tools include `title`, `description`, `inputSchema`, and `annotations`\n- [ ] Annotations correctly set (readOnlyHint, destructiveHint, idempotentHint, openWorldHint)\n- [ ] All tools use Zod schemas for runtime input validation with `.strict()` enforcement\n- [ ] All Zod schemas have proper constraints and descriptive error messages\n- [ ] All tools have comprehensive descriptions with explicit input/output types\n- [ ] Descriptions include return value examples and complete schema documentation\n- [ ] Error messages are clear, actionable, and educational\n\n### TypeScript Quality\n- [ ] TypeScript interfaces are defined for all data structures\n- [ ] Strict TypeScript is enabled in tsconfig.json\n- [ ] No use of `any` type - use `unknown` or proper types instead\n- [ ] All async functions have explicit Promise\u003cT\u003e return types\n- [ ] Error handling uses proper type guards (e.g., `axios.isAxiosError`, `z.ZodError`)\n\n### Advanced Features (where applicable)\n- [ ] Resources registered for appropriate data endpoints\n- [ ] Appropriate transport configured (stdio or streamable HTTP)\n- [ ] Notifications implemented for dynamic server capabilities\n- [ ] Type-safe with SDK interfaces\n\n### Project Configuration\n- [ ] Package.json includes all necessary dependencies\n- [ ] Build script produces working JavaScript in dist/ directory\n- [ ] Main entry point is properly configured as dist/index.js\n- [ ] Server name follows format: `{service}-mcp-server`\n- [ ] tsconfig.json properly configured with strict mode\n\n### Code Quality\n- [ ] Pagination is properly implemented where applicable\n- [ ] Large responses check CHARACTER_LIMIT constant and truncate with clear messages\n- [ ] Filtering options are provided for potentially large result sets\n- [ ] All network operations handle timeouts and connection errors gracefully\n- [ ] Common functionality is extracted into reusable functions\n- [ ] Return types are consistent across similar operations\n\n### Testing and Build\n- [ ] `npm run build` completes successfully without errors\n- [ ] dist/index.js created and executable\n- [ ] Server runs: `node dist/index.js --help`\n- [ ] All imports resolve correctly\n- [ ] Sample tool calls work as expected","reference/python_mcp_server.md":"# Python MCP Server Implementation Guide\n\n## Overview\n\nThis document provides Python-specific best practices and examples for implementing MCP servers using the MCP Python SDK. It covers server setup, tool registration patterns, input validation with Pydantic, error handling, and complete working examples.\n\n---\n\n## Quick Reference\n\n### Key Imports\n```python\nfrom mcp.server.fastmcp import FastMCP\nfrom pydantic import BaseModel, Field, field_validator, ConfigDict\nfrom typing import Optional, List, Dict, Any\nfrom enum import Enum\nimport httpx\n```\n\n### Server Initialization\n```python\nmcp = FastMCP(\"service_mcp\")\n```\n\n### Tool Registration Pattern\n```python\n@mcp.tool(name=\"tool_name\", annotations={...})\nasync def tool_function(params: InputModel) -\u003e str:\n    # Implementation\n    pass\n```\n\n---\n\n## MCP Python SDK and FastMCP\n\nThe official MCP Python SDK provides FastMCP, a high-level framework for building MCP servers. It provides:\n- Automatic description and inputSchema generation from function signatures and docstrings\n- Pydantic model integration for input validation\n- Decorator-based tool registration with `@mcp.tool`\n\n**For complete SDK documentation, use WebFetch to load:**\n`https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.md`\n\n## Server Naming Convention\n\nPython MCP servers must follow this naming pattern:\n- **Format**: `{service}_mcp` (lowercase with underscores)\n- **Examples**: `github_mcp`, `jira_mcp`, `stripe_mcp`\n\nThe name should be:\n- General (not tied to specific features)\n- Descriptive of the service/API being integrated\n- Easy to infer from the task description\n- Without version numbers or dates\n\n## Tool Implementation\n\n### Tool Naming\n\nUse snake_case for tool names (e.g., \"search_users\", \"create_project\", \"get_channel_info\") with clear, action-oriented names.\n\n**Avoid Naming Conflicts**: Include the service context to prevent overlaps:\n- Use \"slack_send_message\" instead of just \"send_message\"\n- Use \"github_create_issue\" instead of just \"create_issue\"\n- Use \"asana_list_tasks\" instead of just \"list_tasks\"\n\n### Tool Structure with FastMCP\n\nTools are defined using the `@mcp.tool` decorator with Pydantic models for input validation:\n\n```python\nfrom pydantic import BaseModel, Field, ConfigDict\nfrom mcp.server.fastmcp import FastMCP\n\n# Initialize the MCP server\nmcp = FastMCP(\"example_mcp\")\n\n# Define Pydantic model for input validation\nclass ServiceToolInput(BaseModel):\n    '''Input model for service tool operation.'''\n    model_config = ConfigDict(\n        str_strip_whitespace=True,  # Auto-strip whitespace from strings\n        validate_assignment=True,    # Validate on assignment\n        extra='forbid'              # Forbid extra fields\n    )\n\n    param1: str = Field(..., description=\"First parameter description (e.g., 'user123', 'project-abc')\", min_length=1, max_length=100)\n    param2: Optional[int] = Field(default=None, description=\"Optional integer parameter with constraints\", ge=0, le=1000)\n    tags: Optional[List[str]] = Field(default_factory=list, description=\"List of tags to apply\", max_items=10)\n\n@mcp.tool(\n    name=\"service_tool_name\",\n    annotations={\n        \"title\": \"Human-Readable Tool Title\",\n        \"readOnlyHint\": True,     # Tool does not modify environment\n        \"destructiveHint\": False,  # Tool does not perform destructive operations\n        \"idempotentHint\": True,    # Repeated calls have no additional effect\n        \"openWorldHint\": False     # Tool does not interact with external entities\n    }\n)\nasync def service_tool_name(params: ServiceToolInput) -\u003e str:\n    '''Tool description automatically becomes the 'description' field.\n\n    This tool performs a specific operation on the service. It validates all inputs\n    using the ServiceToolInput Pydantic model before processing.\n\n    Args:\n        params (ServiceToolInput): Validated input parameters containing:\n            - param1 (str): First parameter description\n            - param2 (Optional[int]): Optional parameter with default\n            - tags (Optional[List[str]]): List of tags\n\n    Returns:\n        str: JSON-formatted response containing operation results\n    '''\n    # Implementation here\n    pass\n```\n\n## Pydantic v2 Key Features\n\n- Use `model_config` instead of nested `Config` class\n- Use `field_validator` instead of deprecated `validator`\n- Use `model_dump()` instead of deprecated `dict()`\n- Validators require `@classmethod` decorator\n- Type hints are required for validator methods\n\n```python\nfrom pydantic import BaseModel, Field, field_validator, ConfigDict\n\nclass CreateUserInput(BaseModel):\n    model_config = ConfigDict(\n        str_strip_whitespace=True,\n        validate_assignment=True\n    )\n\n    name: str = Field(..., description=\"User's full name\", min_length=1, max_length=100)\n    email: str = Field(..., description=\"User's email address\", pattern=r'^[\\w\\.-]+@[\\w\\.-]+\\.\\w+$')\n    age: int = Field(..., description=\"User's age\", ge=0, le=150)\n\n    @field_validator('email')\n    @classmethod\n    def validate_email(cls, v: str) -\u003e str:\n        if not v.strip():\n            raise ValueError(\"Email cannot be empty\")\n        return v.lower()\n```\n\n## Response Format Options\n\nSupport multiple output formats for flexibility:\n\n```python\nfrom enum import Enum\n\nclass ResponseFormat(str, Enum):\n    '''Output format for tool responses.'''\n    MARKDOWN = \"markdown\"\n    JSON = \"json\"\n\nclass UserSearchInput(BaseModel):\n    query: str = Field(..., description=\"Search query\")\n    response_format: ResponseFormat = Field(\n        default=ResponseFormat.MARKDOWN,\n        description=\"Output format: 'markdown' for human-readable or 'json' for machine-readable\"\n    )\n```\n\n**Markdown format**:\n- Use headers, lists, and formatting for clarity\n- Convert timestamps to human-readable format (e.g., \"2024-01-15 10:30:00 UTC\" instead of epoch)\n- Show display names with IDs in parentheses (e.g., \"@john.doe (U123456)\")\n- Omit verbose metadata (e.g., show only one profile image URL, not all sizes)\n- Group related information logically\n\n**JSON format**:\n- Return complete, structured data suitable for programmatic processing\n- Include all available fields and metadata\n- Use consistent field names and types\n\n## Pagination Implementation\n\nFor tools that list resources:\n\n```python\nclass ListInput(BaseModel):\n    limit: Optional[int] = Field(default=20, description=\"Maximum results to return\", ge=1, le=100)\n    offset: Optional[int] = Field(default=0, description=\"Number of results to skip for pagination\", ge=0)\n\nasync def list_items(params: ListInput) -\u003e str:\n    # Make API request with pagination\n    data = await api_request(limit=params.limit, offset=params.offset)\n\n    # Return pagination info\n    response = {\n        \"total\": data[\"total\"],\n        \"count\": len(data[\"items\"]),\n        \"offset\": params.offset,\n        \"items\": data[\"items\"],\n        \"has_more\": data[\"total\"] \u003e params.offset + len(data[\"items\"]),\n        \"next_offset\": params.offset + len(data[\"items\"]) if data[\"total\"] \u003e params.offset + len(data[\"items\"]) else None\n    }\n    return json.dumps(response, indent=2)\n```\n\n## Error Handling\n\nProvide clear, actionable error messages:\n\n```python\ndef _handle_api_error(e: Exception) -\u003e str:\n    '''Consistent error formatting across all tools.'''\n    if isinstance(e, httpx.HTTPStatusError):\n        if e.response.status_code == 404:\n            return \"Error: Resource not found. Please check the ID is correct.\"\n        elif e.response.status_code == 403:\n            return \"Error: Permission denied. You don't have access to this resource.\"\n        elif e.response.status_code == 429:\n            return \"Error: Rate limit exceeded. Please wait before making more requests.\"\n        return f\"Error: API request failed with status {e.response.status_code}\"\n    elif isinstance(e, httpx.TimeoutException):\n        return \"Error: Request timed out. Please try again.\"\n    return f\"Error: Unexpected error occurred: {type(e).__name__}\"\n```\n\n## Shared Utilities\n\nExtract common functionality into reusable functions:\n\n```python\n# Shared API request function\nasync def _make_api_request(endpoint: str, method: str = \"GET\", **kwargs) -\u003e dict:\n    '''Reusable function for all API calls.'''\n    async with httpx.AsyncClient() as client:\n        response = await client.request(\n            method,\n            f\"{API_BASE_URL}/{endpoint}\",\n            timeout=30.0,\n            **kwargs\n        )\n        response.raise_for_status()\n        return response.json()\n```\n\n## Async/Await Best Practices\n\nAlways use async/await for network requests and I/O operations:\n\n```python\n# Good: Async network request\nasync def fetch_data(resource_id: str) -\u003e dict:\n    async with httpx.AsyncClient() as client:\n        response = await client.get(f\"{API_URL}/resource/{resource_id}\")\n        response.raise_for_status()\n        return response.json()\n\n# Bad: Synchronous request\ndef fetch_data(resource_id: str) -\u003e dict:\n    response = requests.get(f\"{API_URL}/resource/{resource_id}\")  # Blocks\n    return response.json()\n```\n\n## Type Hints\n\nUse type hints throughout:\n\n```python\nfrom typing import Optional, List, Dict, Any\n\nasync def get_user(user_id: str) -\u003e Dict[str, Any]:\n    data = await fetch_user(user_id)\n    return {\"id\": data[\"id\"], \"name\": data[\"name\"]}\n```\n\n## Tool Docstrings\n\nEvery tool must have comprehensive docstrings with explicit type information:\n\n```python\nasync def search_users(params: UserSearchInput) -\u003e str:\n    '''\n    Search for users in the Example system by name, email, or team.\n\n    This tool searches across all user profiles in the Example platform,\n    supporting partial matches and various search filters. It does NOT\n    create or modify users, only searches existing ones.\n\n    Args:\n        params (UserSearchInput): Validated input parameters containing:\n            - query (str): Search string to match against names/emails (e.g., \"john\", \"@example.com\", \"team:marketing\")\n            - limit (Optional[int]): Maximum results to return, between 1-100 (default: 20)\n            - offset (Optional[int]): Number of results to skip for pagination (default: 0)\n\n    Returns:\n        str: JSON-formatted string containing search results with the following schema:\n\n        Success response:\n        {\n            \"total\": int,           # Total number of matches found\n            \"count\": int,           # Number of results in this response\n            \"offset\": int,          # Current pagination offset\n            \"users\": [\n                {\n                    \"id\": str,      # User ID (e.g., \"U123456789\")\n                    \"name\": str,    # Full name (e.g., \"John Doe\")\n                    \"email\": str,   # Email address (e.g., \"john@example.com\")\n                    \"team\": str     # Team name (e.g., \"Marketing\") - optional\n                }\n            ]\n        }\n\n        Error response:\n        \"Error: \u003cerror message\u003e\" or \"No users found matching '\u003cquery\u003e'\"\n\n    Examples:\n        - Use when: \"Find all marketing team members\" -\u003e params with query=\"team:marketing\"\n        - Use when: \"Search for John's account\" -\u003e params with query=\"john\"\n        - Don't use when: You need to create a user (use example_create_user instead)\n        - Don't use when: You have a user ID and need full details (use example_get_user instead)\n\n    Error Handling:\n        - Input validation errors are handled by Pydantic model\n        - Returns \"Error: Rate limit exceeded\" if too many requests (429 status)\n        - Returns \"Error: Invalid API authentication\" if API key is invalid (401 status)\n        - Returns formatted list of results or \"No users found matching 'query'\"\n    '''\n```\n\n## Complete Example\n\nSee below for a complete Python MCP server example:\n\n```python\n#!/usr/bin/env python3\n'''\nMCP Server for Example Service.\n\nThis server provides tools to interact with Example API, including user search,\nproject management, and data export capabilities.\n'''\n\nfrom typing import Optional, List, Dict, Any\nfrom enum import Enum\nimport httpx\nfrom pydantic import BaseModel, Field, field_validator, ConfigDict\nfrom mcp.server.fastmcp import FastMCP\n\n# Initialize the MCP server\nmcp = FastMCP(\"example_mcp\")\n\n# Constants\nAPI_BASE_URL = \"https://api.example.com/v1\"\n\n# Enums\nclass ResponseFormat(str, Enum):\n    '''Output format for tool responses.'''\n    MARKDOWN = \"markdown\"\n    JSON = \"json\"\n\n# Pydantic Models for Input Validation\nclass UserSearchInput(BaseModel):\n    '''Input model for user search operations.'''\n    model_config = ConfigDict(\n        str_strip_whitespace=True,\n        validate_assignment=True\n    )\n\n    query: str = Field(..., description=\"Search string to match against names/emails\", min_length=2, max_length=200)\n    limit: Optional[int] = Field(default=20, description=\"Maximum results to return\", ge=1, le=100)\n    offset: Optional[int] = Field(default=0, description=\"Number of results to skip for pagination\", ge=0)\n    response_format: ResponseFormat = Field(default=ResponseFormat.MARKDOWN, description=\"Output format\")\n\n    @field_validator('query')\n    @classmethod\n    def validate_query(cls, v: str) -\u003e str:\n        if not v.strip():\n            raise ValueError(\"Query cannot be empty or whitespace only\")\n        return v.strip()\n\n# Shared utility functions\nasync def _make_api_request(endpoint: str, method: str = \"GET\", **kwargs) -\u003e dict:\n    '''Reusable function for all API calls.'''\n    async with httpx.AsyncClient() as client:\n        response = await client.request(\n            method,\n            f\"{API_BASE_URL}/{endpoint}\",\n            timeout=30.0,\n            **kwargs\n        )\n        response.raise_for_status()\n        return response.json()\n\ndef _handle_api_error(e: Exception) -\u003e str:\n    '''Consistent error formatting across all tools.'''\n    if isinstance(e, httpx.HTTPStatusError):\n        if e.response.status_code == 404:\n            return \"Error: Resource not found. Please check the ID is correct.\"\n        elif e.response.status_code == 403:\n            return \"Error: Permission denied. You don't have access to this resource.\"\n        elif e.response.status_code == 429:\n            return \"Error: Rate limit exceeded. Please wait before making more requests.\"\n        return f\"Error: API request failed with status {e.response.status_code}\"\n    elif isinstance(e, httpx.TimeoutException):\n        return \"Error: Request timed out. Please try again.\"\n    return f\"Error: Unexpected error occurred: {type(e).__name__}\"\n\n# Tool definitions\n@mcp.tool(\n    name=\"example_search_users\",\n    annotations={\n        \"title\": \"Search Example Users\",\n        \"readOnlyHint\": True,\n        \"destructiveHint\": False,\n        \"idempotentHint\": True,\n        \"openWorldHint\": True\n    }\n)\nasync def example_search_users(params: UserSearchInput) -\u003e str:\n    '''Search for users in the Example system by name, email, or team.\n\n    [Full docstring as shown above]\n    '''\n    try:\n        # Make API request using validated parameters\n        data = await _make_api_request(\n            \"users/search\",\n            params={\n                \"q\": params.query,\n                \"limit\": params.limit,\n                \"offset\": params.offset\n            }\n        )\n\n        users = data.get(\"users\", [])\n        total = data.get(\"total\", 0)\n\n        if not users:\n            return f\"No users found matching '{params.query}'\"\n\n        # Format response based on requested format\n        if params.response_format == ResponseFormat.MARKDOWN:\n            lines = [f\"# User Search Results: '{params.query}'\", \"\"]\n            lines.append(f\"Found {total} users (showing {len(users)})\")\n            lines.append(\"\")\n\n            for user in users:\n                lines.append(f\"## {user['name']} ({user['id']})\")\n                lines.append(f\"- **Email**: {user['email']}\")\n                if user.get('team'):\n                    lines.append(f\"- **Team**: {user['team']}\")\n                lines.append(\"\")\n\n            return \"\\n\".join(lines)\n\n        else:\n            # Machine-readable JSON format\n            import json\n            response = {\n                \"total\": total,\n                \"count\": len(users),\n                \"offset\": params.offset,\n                \"users\": users\n            }\n            return json.dumps(response, indent=2)\n\n    except Exception as e:\n        return _handle_api_error(e)\n\nif __name__ == \"__main__\":\n    mcp.run()\n```\n\n---\n\n## Advanced FastMCP Features\n\n### Context Parameter Injection\n\nFastMCP can automatically inject a `Context` parameter into tools for advanced capabilities like logging, progress reporting, resource reading, and user interaction:\n\n```python\nfrom mcp.server.fastmcp import FastMCP, Context\n\nmcp = FastMCP(\"example_mcp\")\n\n@mcp.tool()\nasync def advanced_search(query: str, ctx: Context) -\u003e str:\n    '''Advanced tool with context access for logging and progress.'''\n\n    # Report progress for long operations\n    await ctx.report_progress(0.25, \"Starting search...\")\n\n    # Log information for debugging\n    await ctx.log_info(\"Processing query\", {\"query\": query, \"timestamp\": datetime.now()})\n\n    # Perform search\n    results = await search_api(query)\n    await ctx.report_progress(0.75, \"Formatting results...\")\n\n    # Access server configuration\n    server_name = ctx.fastmcp.name\n\n    return format_results(results)\n\n@mcp.tool()\nasync def interactive_tool(resource_id: str, ctx: Context) -\u003e str:\n    '''Tool that can request additional input from users.'''\n\n    # Request sensitive information when needed\n    api_key = await ctx.elicit(\n        prompt=\"Please provide your API key:\",\n        input_type=\"password\"\n    )\n\n    # Use the provided key\n    return await api_call(resource_id, api_key)\n```\n\n**Context capabilities:**\n- `ctx.report_progress(progress, message)` - Report progress for long operations\n- `ctx.log_info(message, data)` / `ctx.log_error()` / `ctx.log_debug()` - Logging\n- `ctx.elicit(prompt, input_type)` - Request input from users\n- `ctx.fastmcp.name` - Access server configuration\n- `ctx.read_resource(uri)` - Read MCP resources\n\n### Resource Registration\n\nExpose data as resources for efficient, template-based access:\n\n```python\n@mcp.resource(\"file://documents/{name}\")\nasync def get_document(name: str) -\u003e str:\n    '''Expose documents as MCP resources.\n\n    Resources are useful for static or semi-static data that doesn't\n    require complex parameters. They use URI templates for flexible access.\n    '''\n    document_path = f\"./docs/{name}\"\n    with open(document_path, \"r\") as f:\n        return f.read()\n\n@mcp.resource(\"config://settings/{key}\")\nasync def get_setting(key: str, ctx: Context) -\u003e str:\n    '''Expose configuration as resources with context.'''\n    settings = await load_settings()\n    return json.dumps(settings.get(key, {}))\n```\n\n**When to use Resources vs Tools:**\n- **Resources**: For data access with simple parameters (URI templates)\n- **Tools**: For complex operations with validation and business logic\n\n### Structured Output Types\n\nFastMCP supports multiple return types beyond strings:\n\n```python\nfrom typing import TypedDict\nfrom dataclasses import dataclass\nfrom pydantic import BaseModel\n\n# TypedDict for structured returns\nclass UserData(TypedDict):\n    id: str\n    name: str\n    email: str\n\n@mcp.tool()\nasync def get_user_typed(user_id: str) -\u003e UserData:\n    '''Returns structured data - FastMCP handles serialization.'''\n    return {\"id\": user_id, \"name\": \"John Doe\", \"email\": \"john@example.com\"}\n\n# Pydantic models for complex validation\nclass DetailedUser(BaseModel):\n    id: str\n    name: str\n    email: str\n    created_at: datetime\n    metadata: Dict[str, Any]\n\n@mcp.tool()\nasync def get_user_detailed(user_id: str) -\u003e DetailedUser:\n    '''Returns Pydantic model - automatically generates schema.'''\n    user = await fetch_user(user_id)\n    return DetailedUser(**user)\n```\n\n### Lifespan Management\n\nInitialize resources that persist across requests:\n\n```python\nfrom contextlib import asynccontextmanager\n\n@asynccontextmanager\nasync def app_lifespan():\n    '''Manage resources that live for the server's lifetime.'''\n    # Initialize connections, load config, etc.\n    db = await connect_to_database()\n    config = load_configuration()\n\n    # Make available to all tools\n    yield {\"db\": db, \"config\": config}\n\n    # Cleanup on shutdown\n    await db.close()\n\nmcp = FastMCP(\"example_mcp\", lifespan=app_lifespan)\n\n@mcp.tool()\nasync def query_data(query: str, ctx: Context) -\u003e str:\n    '''Access lifespan resources through context.'''\n    db = ctx.request_context.lifespan_state[\"db\"]\n    results = await db.query(query)\n    return format_results(results)\n```\n\n### Transport Options\n\nFastMCP supports two main transport mechanisms:\n\n```python\n# stdio transport (for local tools) - default\nif __name__ == \"__main__\":\n    mcp.run()\n\n# Streamable HTTP transport (for remote servers)\nif __name__ == \"__main__\":\n    mcp.run(transport=\"streamable_http\", port=8000)\n```\n\n**Transport selection:**\n- **stdio**: Command-line tools, local integrations, subprocess execution\n- **Streamable HTTP**: Web services, remote access, multiple clients\n\n---\n\n## Code Best Practices\n\n### Code Composability and Reusability\n\nYour implementation MUST prioritize composability and code reuse:\n\n1. **Extract Common Functionality**:\n   - Create reusable helper functions for operations used across multiple tools\n   - Build shared API clients for HTTP requests instead of duplicating code\n   - Centralize error handling logic in utility functions\n   - Extract business logic into dedicated functions that can be composed\n   - Extract shared markdown or JSON field selection \u0026 formatting functionality\n\n2. **Avoid Duplication**:\n   - NEVER copy-paste similar code between tools\n   - If you find yourself writing similar logic twice, extract it into a function\n   - Common operations like pagination, filtering, field selection, and formatting should be shared\n   - Authentication/authorization logic should be centralized\n\n### Python-Specific Best Practices\n\n1. **Use Type Hints**: Always include type annotations for function parameters and return values\n2. **Pydantic Models**: Define clear Pydantic models for all input validation\n3. **Avoid Manual Validation**: Let Pydantic handle input validation with constraints\n4. **Proper Imports**: Group imports (standard library, third-party, local)\n5. **Error Handling**: Use specific exception types (httpx.HTTPStatusError, not generic Exception)\n6. **Async Context Managers**: Use `async with` for resources that need cleanup\n7. **Constants**: Define module-level constants in UPPER_CASE\n\n## Quality Checklist\n\nBefore finalizing your Python MCP server implementation, ensure:\n\n### Strategic Design\n- [ ] Tools enable complete workflows, not just API endpoint wrappers\n- [ ] Tool names reflect natural task subdivisions\n- [ ] Response formats optimize for agent context efficiency\n- [ ] Human-readable identifiers used where appropriate\n- [ ] Error messages guide agents toward correct usage\n\n### Implementation Quality\n- [ ] FOCUSED IMPLEMENTATION: Most important and valuable tools implemented\n- [ ] All tools have descriptive names and documentation\n- [ ] Return types are consistent across similar operations\n- [ ] Error handling is implemented for all external calls\n- [ ] Server name follows format: `{service}_mcp`\n- [ ] All network operations use async/await\n- [ ] Common functionality is extracted into reusable functions\n- [ ] Error messages are clear, actionable, and educational\n- [ ] Outputs are properly validated and formatted\n\n### Tool Configuration\n- [ ] All tools implement 'name' and 'annotations' in the decorator\n- [ ] Annotations correctly set (readOnlyHint, destructiveHint, idempotentHint, openWorldHint)\n- [ ] All tools use Pydantic BaseModel for input validation with Field() definitions\n- [ ] All Pydantic Fields have explicit types and descriptions with constraints\n- [ ] All tools have comprehensive docstrings with explicit input/output types\n- [ ] Docstrings include complete schema structure for dict/JSON returns\n- [ ] Pydantic models handle input validation (no manual validation needed)\n\n### Advanced Features (where applicable)\n- [ ] Context injection used for logging, progress, or elicitation\n- [ ] Resources registered for appropriate data endpoints\n- [ ] Lifespan management implemented for persistent connections\n- [ ] Structured output types used (TypedDict, Pydantic models)\n- [ ] Appropriate transport configured (stdio or streamable HTTP)\n\n### Code Quality\n- [ ] File includes proper imports including Pydantic imports\n- [ ] Pagination is properly implemented where applicable\n- [ ] Filtering options are provided for potentially large result sets\n- [ ] All async functions are properly defined with `async def`\n- [ ] HTTP client usage follows async patterns with proper context managers\n- [ ] Type hints are used throughout the code\n- [ ] Constants are defined at module level in UPPER_CASE\n\n### Testing\n- [ ] Server runs successfully: `python your_server.py --help`\n- [ ] All imports resolve correctly\n- [ ] Sample tool calls work as expected\n- [ ] Error scenarios handled gracefully","scripts/connections.py":"\"\"\"Lightweight connection handling for MCP servers.\"\"\"\n\nfrom abc import ABC, abstractmethod\nfrom contextlib import AsyncExitStack\nfrom typing import Any\n\nfrom mcp import ClientSession, StdioServerParameters\nfrom mcp.client.sse import sse_client\nfrom mcp.client.stdio import stdio_client\nfrom mcp.client.streamable_http import streamablehttp_client\n\n\nclass MCPConnection(ABC):\n    \"\"\"Base class for MCP server connections.\"\"\"\n\n    def __init__(self):\n        self.session = None\n        self._stack = None\n\n    @abstractmethod\n    def _create_context(self):\n        \"\"\"Create the connection context based on connection type.\"\"\"\n\n    async def __aenter__(self):\n        \"\"\"Initialize MCP server connection.\"\"\"\n        self._stack = AsyncExitStack()\n        await self._stack.__aenter__()\n\n        try:\n            ctx = self._create_context()\n            result = await self._stack.enter_async_context(ctx)\n\n            if len(result) == 2:\n                read, write = result\n            elif len(result) == 3:\n                read, write, _ = result\n            else:\n                raise ValueError(f\"Unexpected context result: {result}\")\n\n            session_ctx = ClientSession(read, write)\n            self.session = await self._stack.enter_async_context(session_ctx)\n            await self.session.initialize()\n            return self\n        except BaseException:\n            await self._stack.__aexit__(None, None, None)\n            raise\n\n    async def __aexit__(self, exc_type, exc_val, exc_tb):\n        \"\"\"Clean up MCP server connection resources.\"\"\"\n        if self._stack:\n            await self._stack.__aexit__(exc_type, exc_val, exc_tb)\n        self.session = None\n        self._stack = None\n\n    async def list_tools(self) -\u003e list[dict[str, Any]]:\n        \"\"\"Retrieve available tools from the MCP server.\"\"\"\n        response = await self.session.list_tools()\n        return [\n            {\n                \"name\": tool.name,\n                \"description\": tool.description,\n                \"input_schema\": tool.inputSchema,\n            }\n            for tool in response.tools\n        ]\n\n    async def call_tool(self, tool_name: str, arguments: dict[str, Any]) -\u003e Any:\n        \"\"\"Call a tool on the MCP server with provided arguments.\"\"\"\n        result = await self.session.call_tool(tool_name, arguments=arguments)\n        return result.content\n\n\nclass MCPConnectionStdio(MCPConnection):\n    \"\"\"MCP connection using standard input/output.\"\"\"\n\n    def __init__(self, command: str, args: list[str] = None, env: dict[str, str] = None):\n        super().__init__()\n        self.command = command\n        self.args = args or []\n        self.env = env\n\n    def _create_context(self):\n        return stdio_client(\n            StdioServerParameters(command=self.command, args=self.args, env=self.env)\n        )\n\n\nclass MCPConnectionSSE(MCPConnection):\n    \"\"\"MCP connection using Server-Sent Events.\"\"\"\n\n    def __init__(self, url: str, headers: dict[str, str] = None):\n        super().__init__()\n        self.url = url\n        self.headers = headers or {}\n\n    def _create_context(self):\n        return sse_client(url=self.url, headers=self.headers)\n\n\nclass MCPConnectionHTTP(MCPConnection):\n    \"\"\"MCP connection using Streamable HTTP.\"\"\"\n\n    def __init__(self, url: str, headers: dict[str, str] = None):\n        super().__init__()\n        self.url = url\n        self.headers = headers or {}\n\n    def _create_context(self):\n        return streamablehttp_client(url=self.url, headers=self.headers)\n\n\ndef create_connection(\n    transport: str,\n    command: str = None,\n    args: list[str] = None,\n    env: dict[str, str] = None,\n    url: str = None,\n    headers: dict[str, str] = None,\n) -\u003e MCPConnection:\n    \"\"\"Factory function to create the appropriate MCP connection.\n\n    Args:\n        transport: Connection type (\"stdio\", \"sse\", or \"http\")\n        command: Command to run (stdio only)\n        args: Command arguments (stdio only)\n        env: Environment variables (stdio only)\n        url: Server URL (sse and http only)\n        headers: HTTP headers (sse and http only)\n\n    Returns:\n        MCPConnection instance\n    \"\"\"\n    transport = transport.lower()\n\n    if transport == \"stdio\":\n        if not command:\n            raise ValueError(\"Command is required for stdio transport\")\n        return MCPConnectionStdio(command=command, args=args, env=env)\n\n    elif transport == \"sse\":\n        if not url:\n            raise ValueError(\"URL is required for sse transport\")\n        return MCPConnectionSSE(url=url, headers=headers)\n\n    elif transport in [\"http\", \"streamable_http\", \"streamable-http\"]:\n        if not url:\n            raise ValueError(\"URL is required for http transport\")\n        return MCPConnectionHTTP(url=url, headers=headers)\n\n    else:\n        raise ValueError(f\"Unsupported transport type: {transport}. Use 'stdio', 'sse', or 'http'\")\n","scripts/evaluation.py":"\"\"\"MCP Server Evaluation Harness\n\nThis script evaluates MCP servers by running test questions against them using Claude.\n\"\"\"\n\nimport argparse\nimport asyncio\nimport json\nimport re\nimport sys\nimport time\nimport traceback\nimport xml.etree.ElementTree as ET\nfrom pathlib import Path\nfrom typing import Any\n\nfrom anthropic import Anthropic\n\nfrom connections import create_connection\n\nEVALUATION_PROMPT = \"\"\"You are an AI assistant with access to tools.\n\nWhen given a task, you MUST:\n1. Use the available tools to complete the task\n2. Provide summary of each step in your approach, wrapped in \u003csummary\u003e tags\n3. Provide feedback on the tools provided, wrapped in \u003cfeedback\u003e tags\n4. Provide your final response, wrapped in \u003cresponse\u003e tags\n\nSummary Requirements:\n- In your \u003csummary\u003e tags, you must explain:\n  - The steps you took to complete the task\n  - Which tools you used, in what order, and why\n  - The inputs you provided to each tool\n  - The outputs you received from each tool\n  - A summary for how you arrived at the response\n\nFeedback Requirements:\n- In your \u003cfeedback\u003e tags, provide constructive feedback on the tools:\n  - Comment on tool names: Are they clear and descriptive?\n  - Comment on input parameters: Are they well-documented? Are required vs optional parameters clear?\n  - Comment on descriptions: Do they accurately describe what the tool does?\n  - Comment on any errors encountered during tool usage: Did the tool fail to execute? Did the tool return too many tokens?\n  - Identify specific areas for improvement and explain WHY they would help\n  - Be specific and actionable in your suggestions\n\nResponse Requirements:\n- Your response should be concise and directly address what was asked\n- Always wrap your final response in \u003cresponse\u003e tags\n- If you cannot solve the task return \u003cresponse\u003eNOT_FOUND\u003c/response\u003e\n- For numeric responses, provide just the number\n- For IDs, provide just the ID\n- For names or text, provide the exact text requested\n- Your response should go last\"\"\"\n\n\ndef parse_evaluation_file(file_path: Path) -\u003e list[dict[str, Any]]:\n    \"\"\"Parse XML evaluation file with qa_pair elements.\"\"\"\n    try:\n        tree = ET.parse(file_path)\n        root = tree.getroot()\n        evaluations = []\n\n        for qa_pair in root.findall(\".//qa_pair\"):\n            question_elem = qa_pair.find(\"question\")\n            answer_elem = qa_pair.find(\"answer\")\n\n            if question_elem is not None and answer_elem is not None:\n                evaluations.append({\n                    \"question\": (question_elem.text or \"\").strip(),\n                    \"answer\": (answer_elem.text or \"\").strip(),\n                })\n\n        return evaluations\n    except Exception as e:\n        print(f\"Error parsing evaluation file {file_path}: {e}\")\n        return []\n\n\ndef extract_xml_content(text: str, tag: str) -\u003e str | None:\n    \"\"\"Extract content from XML tags.\"\"\"\n    pattern = rf\"\u003c{tag}\u003e(.*?)\u003c/{tag}\u003e\"\n    matches = re.findall(pattern, text, re.DOTALL)\n    return matches[-1].strip() if matches else None\n\n\nasync def agent_loop(\n    client: Anthropic,\n    model: str,\n    question: str,\n    tools: list[dict[str, Any]],\n    connection: Any,\n) -\u003e tuple[str, dict[str, Any]]:\n    \"\"\"Run the agent loop with MCP tools.\"\"\"\n    messages = [{\"role\": \"user\", \"content\": question}]\n\n    response = await asyncio.to_thread(\n        client.messages.create,\n        model=model,\n        max_tokens=4096,\n        system=EVALUATION_PROMPT,\n        messages=messages,\n        tools=tools,\n    )\n\n    messages.append({\"role\": \"assistant\", \"content\": response.content})\n\n    tool_metrics = {}\n\n    while response.stop_reason == \"tool_use\":\n        tool_use = next(block for block in response.content if block.type == \"tool_use\")\n        tool_name = tool_use.name\n        tool_input = tool_use.input\n\n        tool_start_ts = time.time()\n        try:\n            tool_result = await connection.call_tool(tool_name, tool_input)\n            tool_response = json.dumps(tool_result) if isinstance(tool_result, (dict, list)) else str(tool_result)\n        except Exception as e:\n            tool_response = f\"Error executing tool {tool_name}: {str(e)}\\n\"\n            tool_response += traceback.format_exc()\n        tool_duration = time.time() - tool_start_ts\n\n        if tool_name not in tool_metrics:\n            tool_metrics[tool_name] = {\"count\": 0, \"durations\": []}\n        tool_metrics[tool_name][\"count\"] += 1\n        tool_metrics[tool_name][\"durations\"].append(tool_duration)\n\n        messages.append({\n            \"role\": \"user\",\n            \"content\": [{\n                \"type\": \"tool_result\",\n                \"tool_use_id\": tool_use.id,\n                \"content\": tool_response,\n            }]\n        })\n\n        response = await asyncio.to_thread(\n            client.messages.create,\n            model=model,\n            max_tokens=4096,\n            system=EVALUATION_PROMPT,\n            messages=messages,\n            tools=tools,\n        )\n        messages.append({\"role\": \"assistant\", \"content\": response.content})\n\n    response_text = next(\n        (block.text for block in response.content if hasattr(block, \"text\")),\n        None,\n    )\n    return response_text, tool_metrics\n\n\nasync def evaluate_single_task(\n    client: Anthropic,\n    model: str,\n    qa_pair: dict[str, Any],\n    tools: list[dict[str, Any]],\n    connection: Any,\n    task_index: int,\n) -\u003e dict[str, Any]:\n    \"\"\"Evaluate a single QA pair with the given tools.\"\"\"\n    start_time = time.time()\n\n    print(f\"Task {task_index + 1}: Running task with question: {qa_pair['question']}\")\n    response, tool_metrics = await agent_loop(client, model, qa_pair[\"question\"], tools, connection)\n\n    response_value = extract_xml_content(response, \"response\")\n    summary = extract_xml_content(response, \"summary\")\n    feedback = extract_xml_content(response, \"feedback\")\n\n    duration_seconds = time.time() - start_time\n\n    return {\n        \"question\": qa_pair[\"question\"],\n        \"expected\": qa_pair[\"answer\"],\n        \"actual\": response_value,\n        \"score\": int(response_value == qa_pair[\"answer\"]) if response_value else 0,\n        \"total_duration\": duration_seconds,\n        \"tool_calls\": tool_metrics,\n        \"num_tool_calls\": sum(len(metrics[\"durations\"]) for metrics in tool_metrics.values()),\n        \"summary\": summary,\n        \"feedback\": feedback,\n    }\n\n\nREPORT_HEADER = \"\"\"\n# Evaluation Report\n\n## Summary\n\n- **Accuracy**: {correct}/{total} ({accuracy:.1f}%)\n- **Average Task Duration**: {average_duration_s:.2f}s\n- **Average Tool Calls per Task**: {average_tool_calls:.2f}\n- **Total Tool Calls**: {total_tool_calls}\n\n---\n\"\"\"\n\nTASK_TEMPLATE = \"\"\"\n### Task {task_num}\n\n**Question**: {question}\n**Ground Truth Answer**: `{expected_answer}`\n**Actual Answer**: `{actual_answer}`\n**Correct**: {correct_indicator}\n**Duration**: {total_duration:.2f}s\n**Tool Calls**: {tool_calls}\n\n**Summary**\n{summary}\n\n**Feedback**\n{feedback}\n\n---\n\"\"\"\n\n\nasync def run_evaluation(\n    eval_path: Path,\n    connection: Any,\n    model: str = \"claude-3-7-sonnet-20250219\",\n) -\u003e str:\n    \"\"\"Run evaluation with MCP server tools.\"\"\"\n    print(\"🚀 Starting Evaluation\")\n\n    client = Anthropic()\n\n    tools = await connection.list_tools()\n    print(f\"📋 Loaded {len(tools)} tools from MCP server\")\n\n    qa_pairs = parse_evaluation_file(eval_path)\n    print(f\"📋 Loaded {len(qa_pairs)} evaluation tasks\")\n\n    results = []\n    for i, qa_pair in enumerate(qa_pairs):\n        print(f\"Processing task {i + 1}/{len(qa_pairs)}\")\n        result = await evaluate_single_task(client, model, qa_pair, tools, connection, i)\n        results.append(result)\n\n    correct = sum(r[\"score\"] for r in results)\n    accuracy = (correct / len(results)) * 100 if results else 0\n    average_duration_s = sum(r[\"total_duration\"] for r in results) / len(results) if results else 0\n    average_tool_calls = sum(r[\"num_tool_calls\"] for r in results) / len(results) if results else 0\n    total_tool_calls = sum(r[\"num_tool_calls\"] for r in results)\n\n    report = REPORT_HEADER.format(\n        correct=correct,\n        total=len(results),\n        accuracy=accuracy,\n        average_duration_s=average_duration_s,\n        average_tool_calls=average_tool_calls,\n        total_tool_calls=total_tool_calls,\n    )\n\n    report += \"\".join([\n        TASK_TEMPLATE.format(\n            task_num=i + 1,\n            question=qa_pair[\"question\"],\n            expected_answer=qa_pair[\"answer\"],\n            actual_answer=result[\"actual\"] or \"N/A\",\n            correct_indicator=\"✅\" if result[\"score\"] else \"❌\",\n            total_duration=result[\"total_duration\"],\n            tool_calls=json.dumps(result[\"tool_calls\"], indent=2),\n            summary=result[\"summary\"] or \"N/A\",\n            feedback=result[\"feedback\"] or \"N/A\",\n        )\n        for i, (qa_pair, result) in enumerate(zip(qa_pairs, results))\n    ])\n\n    return report\n\n\ndef parse_headers(header_list: list[str]) -\u003e dict[str, str]:\n    \"\"\"Parse header strings in format 'Key: Value' into a dictionary.\"\"\"\n    headers = {}\n    if not header_list:\n        return headers\n\n    for header in header_list:\n        if \":\" in header:\n            key, value = header.split(\":\", 1)\n            headers[key.strip()] = value.strip()\n        else:\n            print(f\"Warning: Ignoring malformed header: {header}\")\n    return headers\n\n\ndef parse_env_vars(env_list: list[str]) -\u003e dict[str, str]:\n    \"\"\"Parse environment variable strings in format 'KEY=VALUE' into a dictionary.\"\"\"\n    env = {}\n    if not env_list:\n        return env\n\n    for env_var in env_list:\n        if \"=\" in env_var:\n            key, value = env_var.split(\"=\", 1)\n            env[key.strip()] = value.strip()\n        else:\n            print(f\"Warning: Ignoring malformed environment variable: {env_var}\")\n    return env\n\n\nasync def main():\n    parser = argparse.ArgumentParser(\n        description=\"Evaluate MCP servers using test questions\",\n        formatter_class=argparse.RawDescriptionHelpFormatter,\n        epilog=\"\"\"\nExamples:\n  # Evaluate a local stdio MCP server\n  python evaluation.py -t stdio -c python -a my_server.py eval.xml\n\n  # Evaluate an SSE MCP server\n  python evaluation.py -t sse -u https://example.com/mcp -H \"Authorization: Bearer token\" eval.xml\n\n  # Evaluate an HTTP MCP server with custom model\n  python evaluation.py -t http -u https://example.com/mcp -m claude-3-5-sonnet-20241022 eval.xml\n        \"\"\",\n    )\n\n    parser.add_argument(\"eval_file\", type=Path, help=\"Path to evaluation XML file\")\n    parser.add_argument(\"-t\", \"--transport\", choices=[\"stdio\", \"sse\", \"http\"], default=\"stdio\", help=\"Transport type (default: stdio)\")\n    parser.add_argument(\"-m\", \"--model\", default=\"claude-3-7-sonnet-20250219\", help=\"Claude model to use (default: claude-3-7-sonnet-20250219)\")\n\n    stdio_group = parser.add_argument_group(\"stdio options\")\n    stdio_group.add_argument(\"-c\", \"--command\", help=\"Command to run MCP server (stdio only)\")\n    stdio_group.add_argument(\"-a\", \"--args\", nargs=\"+\", help=\"Arguments for the command (stdio only)\")\n    stdio_group.add_argument(\"-e\", \"--env\", nargs=\"+\", help=\"Environment variables in KEY=VALUE format (stdio only)\")\n\n    remote_group = parser.add_argument_group(\"sse/http options\")\n    remote_group.add_argument(\"-u\", \"--url\", help=\"MCP server URL (sse/http only)\")\n    remote_group.add_argument(\"-H\", \"--header\", nargs=\"+\", dest=\"headers\", help=\"HTTP headers in 'Key: Value' format (sse/http only)\")\n\n    parser.add_argument(\"-o\", \"--output\", type=Path, help=\"Output file for evaluation report (default: stdout)\")\n\n    args = parser.parse_args()\n\n    if not args.eval_file.exists():\n        print(f\"Error: Evaluation file not found: {args.eval_file}\")\n        sys.exit(1)\n\n    headers = parse_headers(args.headers) if args.headers else None\n    env_vars = parse_env_vars(args.env) if args.env else None\n\n    try:\n        connection = create_connection(\n            transport=args.transport,\n            command=args.command,\n            args=args.args,\n            env=env_vars,\n            url=args.url,\n            headers=headers,\n        )\n    except ValueError as e:\n        print(f\"Error: {e}\")\n        sys.exit(1)\n\n    print(f\"🔗 Connecting to MCP server via {args.transport}...\")\n\n    async with connection:\n        print(\"✅ Connected successfully\")\n        report = await run_evaluation(args.eval_file, connection, args.model)\n\n        if args.output:\n            args.output.write_text(report)\n            print(f\"\\n✅ Report saved to {args.output}\")\n        else:\n            print(\"\\n\" + report)\n\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n","scripts/example_evaluation.xml":"\u003cevaluation\u003e\n   \u003cqa_pair\u003e\n      \u003cquestion\u003eCalculate the compound interest on $10,000 invested at 5% annual interest rate, compounded monthly for 3 years. What is the final amount in dollars (rounded to 2 decimal places)?\u003c/question\u003e\n      \u003canswer\u003e11614.72\u003c/answer\u003e\n   \u003c/qa_pair\u003e\n   \u003cqa_pair\u003e\n      \u003cquestion\u003eA projectile is launched at a 45-degree angle with an initial velocity of 50 m/s. Calculate the total distance (in meters) it has traveled from the launch point after 2 seconds, assuming g=9.8 m/s². Round to 2 decimal places.\u003c/question\u003e\n      \u003canswer\u003e87.25\u003c/answer\u003e\n   \u003c/qa_pair\u003e\n   \u003cqa_pair\u003e\n      \u003cquestion\u003eA sphere has a volume of 500 cubic meters. Calculate its surface area in square meters. Round to 2 decimal places.\u003c/question\u003e\n      \u003canswer\u003e304.65\u003c/answer\u003e\n   \u003c/qa_pair\u003e\n   \u003cqa_pair\u003e\n      \u003cquestion\u003eCalculate the population standard deviation of this dataset: [12, 15, 18, 22, 25, 30, 35]. Round to 2 decimal places.\u003c/question\u003e\n      \u003canswer\u003e7.61\u003c/answer\u003e\n   \u003c/qa_pair\u003e\n   \u003cqa_pair\u003e\n      \u003cquestion\u003eCalculate the pH of a solution with a hydrogen ion concentration of 3.5 × 10^-5 M. Round to 2 decimal places.\u003c/question\u003e\n      \u003canswer\u003e4.46\u003c/answer\u003e\n   \u003c/qa_pair\u003e\n\u003c/evaluation\u003e\n","scripts/requirements.txt":"anthropic\u003e=0.39.0\nmcp\u003e=1.1.0\n"},"import":{"commit_sha":"6a5bb06904ab164a345e41c381fc9097954b83da","imported_at":"2026-05-18T20:11:01Z","license_text":"\n                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright 2026 Anthropic, PBC.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.","owner":"anthropics","repo":"anthropics/skills","source_url":"https://github.com/anthropics/skills/tree/6a5bb06904ab164a345e41c381fc9097954b83da/skills/mcp-builder"}},"content_hash":[59,27,59,8,183,83,191,201,249,153,59,85,164,51,60,179,76,226,37,132,66,252,130,15,48,120,87,121,27,70,217,89],"trust_level":"unsigned","yanked":false}
