hive-skills 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +28 -0
- package/README.md +235 -0
- package/assets/LICENSE +32 -0
- package/assets/THIRD_PARTY_NOTICES.md +72 -0
- package/assets/manifest.json +1290 -0
- package/assets/skills/authored/code-review/composable/BUNDLE.md +192 -0
- package/assets/skills/authored/code-review/composable/INDEX.md +13 -0
- package/assets/skills/authored/code-review/composable/VERSION +1 -0
- package/assets/skills/authored/code-review/composable/mini/01-review-method.md +34 -0
- package/assets/skills/authored/code-review/composable/mini/02-security-review.md +20 -0
- package/assets/skills/authored/code-review/composable/mini/03-correctness-bugs.md +19 -0
- package/assets/skills/authored/code-review/composable/mini/04-concurrency.md +16 -0
- package/assets/skills/authored/code-review/composable/mini/05-error-handling.md +12 -0
- package/assets/skills/authored/code-review/composable/mini/06-performance.md +11 -0
- package/assets/skills/authored/code-review/composable/mini/07-api-design.md +20 -0
- package/assets/skills/authored/code-review/composable/mini/08-missing-tests.md +25 -0
- package/assets/skills/authored/code-review/composable/mini/09-refactoring-and-communication.md +32 -0
- package/assets/skills/authored/data-analysis/composable/BUNDLE.md +186 -0
- package/assets/skills/authored/data-analysis/composable/INDEX.md +13 -0
- package/assets/skills/authored/data-analysis/composable/VERSION +1 -0
- package/assets/skills/authored/data-analysis/composable/mini/01-data-quality-profiling.md +26 -0
- package/assets/skills/authored/data-analysis/composable/mini/02-aggregation-pitfalls.md +21 -0
- package/assets/skills/authored/data-analysis/composable/mini/03-time-series.md +19 -0
- package/assets/skills/authored/data-analysis/composable/mini/04-segmentation.md +23 -0
- package/assets/skills/authored/data-analysis/composable/mini/05-discount-pricing.md +17 -0
- package/assets/skills/authored/data-analysis/composable/mini/06-insight-generation.md +25 -0
- package/assets/skills/authored/data-analysis/composable/mini/07-executive-writing.md +26 -0
- package/assets/skills/authored/data-analysis/composable/mini/08-recommendations.md +20 -0
- package/assets/skills/authored/data-analysis/composable/mini/09-reproducibility-assumptions.md +20 -0
- package/assets/skills/authored/financial-analysis/composable/BUNDLE.md +1293 -0
- package/assets/skills/authored/financial-analysis/composable/INDEX.md +17 -0
- package/assets/skills/authored/financial-analysis/composable/VERSION +1 -0
- package/assets/skills/authored/financial-analysis/composable/mini/00-core.md +69 -0
- package/assets/skills/authored/financial-analysis/composable/mini/01-profitability-efficiency-ratios.md +173 -0
- package/assets/skills/authored/financial-analysis/composable/mini/02-liquidity-leverage-ratios.md +120 -0
- package/assets/skills/authored/financial-analysis/composable/mini/03-valuation-ratios-interpretation.md +107 -0
- package/assets/skills/authored/financial-analysis/composable/mini/04-dcf-projection-wacc.md +122 -0
- package/assets/skills/authored/financial-analysis/composable/mini/05-dcf-terminal-value-sensitivity.md +75 -0
- package/assets/skills/authored/financial-analysis/composable/mini/06-comparables-precedents.md +78 -0
- package/assets/skills/authored/financial-analysis/composable/mini/07-budget-variance-analysis.md +47 -0
- package/assets/skills/authored/financial-analysis/composable/mini/08-driver-based-forecasting-scenarios.md +111 -0
- package/assets/skills/authored/financial-analysis/composable/mini/09-rolling-forecasts-accuracy.md +114 -0
- package/assets/skills/authored/financial-analysis/composable/mini/10-reporting-exec-summary.md +58 -0
- package/assets/skills/authored/financial-analysis/composable/mini/11-industry-adaptations.md +130 -0
- package/assets/skills/authored/financial-analysis/composable/mini/12-toolkit-scripts-io.md +102 -0
- package/assets/skills/authored/python-api/composable/BUNDLE.md +389 -0
- package/assets/skills/authored/python-api/composable/INDEX.md +13 -0
- package/assets/skills/authored/python-api/composable/VERSION +1 -0
- package/assets/skills/authored/python-api/composable/mini/01-project-structure.md +44 -0
- package/assets/skills/authored/python-api/composable/mini/02-routing-and-app.md +38 -0
- package/assets/skills/authored/python-api/composable/mini/03-pydantic-models.md +45 -0
- package/assets/skills/authored/python-api/composable/mini/04-validation-and-errors.md +59 -0
- package/assets/skills/authored/python-api/composable/mini/05-dependencies-and-auth.md +60 -0
- package/assets/skills/authored/python-api/composable/mini/06-pagination-filtering.md +44 -0
- package/assets/skills/authored/python-api/composable/mini/07-async-performance.md +30 -0
- package/assets/skills/authored/python-api/composable/mini/08-testing.md +45 -0
- package/assets/skills/authored/python-api/composable/mini/09-middleware-observability.md +29 -0
- package/assets/skills/authored/tech-writing/composable/BUNDLE.md +220 -0
- package/assets/skills/authored/tech-writing/composable/INDEX.md +12 -0
- package/assets/skills/authored/tech-writing/composable/VERSION +1 -0
- package/assets/skills/authored/tech-writing/composable/mini/01-audience-analysis.md +26 -0
- package/assets/skills/authored/tech-writing/composable/mini/02-document-types.md +27 -0
- package/assets/skills/authored/tech-writing/composable/mini/03-readme-quickstart-changelog.md +22 -0
- package/assets/skills/authored/tech-writing/composable/mini/04-information-architecture.md +21 -0
- package/assets/skills/authored/tech-writing/composable/mini/05-style-clarity.md +29 -0
- package/assets/skills/authored/tech-writing/composable/mini/06-breaking-changes-migrations.md +33 -0
- package/assets/skills/authored/tech-writing/composable/mini/07-troubleshooting-security.md +30 -0
- package/assets/skills/authored/tech-writing/composable/mini/08-faq-voice-tone.md +32 -0
- package/assets/skills/converted/claude-api/composable/BUNDLE.md +14996 -0
- package/assets/skills/converted/claude-api/composable/INDEX.md +98 -0
- package/assets/skills/converted/claude-api/composable/VERSION +1 -0
- package/assets/skills/converted/claude-api/composable/mini/00-core.md +235 -0
- package/assets/skills/converted/claude-api/composable/mini/01-model-api-quick-reference.md +258 -0
- package/assets/skills/converted/claude-api/composable/mini/02-common-pitfalls.md +42 -0
- package/assets/skills/converted/claude-api/composable/mini/10-models.md +135 -0
- package/assets/skills/converted/claude-api/composable/mini/11-platform-availability.md +96 -0
- package/assets/skills/converted/claude-api/composable/mini/12-claude-platform-on-aws.md +59 -0
- package/assets/skills/converted/claude-api/composable/mini/13-live-sources.md +143 -0
- package/assets/skills/converted/claude-api/composable/mini/14-error-codes.md +256 -0
- package/assets/skills/converted/claude-api/composable/mini/15-prompt-caching.md +223 -0
- package/assets/skills/converted/claude-api/composable/mini/16-token-counting.md +56 -0
- package/assets/skills/converted/claude-api/composable/mini/17-tool-use-concepts.md +444 -0
- package/assets/skills/converted/claude-api/composable/mini/18-agent-design.md +101 -0
- package/assets/skills/converted/claude-api/composable/mini/19-anthropic-cli.md +246 -0
- package/assets/skills/converted/claude-api/composable/mini/20-model-migration.md +1301 -0
- package/assets/skills/converted/claude-api/composable/mini/30-managed-agents-overview.md +71 -0
- package/assets/skills/converted/claude-api/composable/mini/31-managed-agents-core.md +278 -0
- package/assets/skills/converted/claude-api/composable/mini/32-managed-agents-environments.md +219 -0
- package/assets/skills/converted/claude-api/composable/mini/33-managed-agents-tools.md +366 -0
- package/assets/skills/converted/claude-api/composable/mini/34-managed-agents-events.md +252 -0
- package/assets/skills/converted/claude-api/composable/mini/35-managed-agents-outcomes.md +106 -0
- package/assets/skills/converted/claude-api/composable/mini/36-managed-agents-multiagent.md +101 -0
- package/assets/skills/converted/claude-api/composable/mini/37-managed-agents-webhooks.md +123 -0
- package/assets/skills/converted/claude-api/composable/mini/38-managed-agents-memory.md +197 -0
- package/assets/skills/converted/claude-api/composable/mini/39-managed-agents-scheduled-deployments.md +146 -0
- package/assets/skills/converted/claude-api/composable/mini/40-managed-agents-client-patterns.md +211 -0
- package/assets/skills/converted/claude-api/composable/mini/41-managed-agents-onboarding.md +82 -0
- package/assets/skills/converted/claude-api/composable/mini/42-managed-agents-api-reference.md +441 -0
- package/assets/skills/converted/claude-api/composable/mini/43-managed-agents-self-hosted-sandboxes.md +174 -0
- package/assets/skills/converted/claude-api/composable/mini/50-python-readme.md +564 -0
- package/assets/skills/converted/claude-api/composable/mini/51-python-tool-use.md +590 -0
- package/assets/skills/converted/claude-api/composable/mini/52-python-streaming-batches-files.md +549 -0
- package/assets/skills/converted/claude-api/composable/mini/53-python-managed-agents.md +335 -0
- package/assets/skills/converted/claude-api/composable/mini/55-typescript-readme.md +404 -0
- package/assets/skills/converted/claude-api/composable/mini/56-typescript-tool-use.md +548 -0
- package/assets/skills/converted/claude-api/composable/mini/57-typescript-streaming-batches-files.md +384 -0
- package/assets/skills/converted/claude-api/composable/mini/58-typescript-managed-agents.md +358 -0
- package/assets/skills/converted/claude-api/composable/mini/60-csharp-readme.md +361 -0
- package/assets/skills/converted/claude-api/composable/mini/61-csharp-tool-use.md +163 -0
- package/assets/skills/converted/claude-api/composable/mini/62-csharp-streaming-batches-files.md +64 -0
- package/assets/skills/converted/claude-api/composable/mini/65-go-readme.md +185 -0
- package/assets/skills/converted/claude-api/composable/mini/66-go-tool-use.md +219 -0
- package/assets/skills/converted/claude-api/composable/mini/67-go-streaming-files.md +63 -0
- package/assets/skills/converted/claude-api/composable/mini/68-go-managed-agents.md +564 -0
- package/assets/skills/converted/claude-api/composable/mini/70-java-readme.md +237 -0
- package/assets/skills/converted/claude-api/composable/mini/71-java-tool-use.md +227 -0
- package/assets/skills/converted/claude-api/composable/mini/72-java-streaming-files.md +49 -0
- package/assets/skills/converted/claude-api/composable/mini/73-java-managed-agents.md +443 -0
- package/assets/skills/converted/claude-api/composable/mini/75-php-readme.md +173 -0
- package/assets/skills/converted/claude-api/composable/mini/76-php-tool-use.md +252 -0
- package/assets/skills/converted/claude-api/composable/mini/77-php-streaming-batches-files.md +53 -0
- package/assets/skills/converted/claude-api/composable/mini/78-php-managed-agents.md +443 -0
- package/assets/skills/converted/claude-api/composable/mini/80-ruby-readme.md +133 -0
- package/assets/skills/converted/claude-api/composable/mini/81-ruby-tool-use-streaming.md +56 -0
- package/assets/skills/converted/claude-api/composable/mini/82-ruby-managed-agents.md +394 -0
- package/assets/skills/converted/claude-api/composable/mini/85-curl-examples.md +255 -0
- package/assets/skills/converted/claude-api/composable/mini/86-curl-managed-agents.md +340 -0
- package/assets/skills/converted/claude-api/composable/presets/csharp.md +1151 -0
- package/assets/skills/converted/claude-api/composable/presets/curl.md +1154 -0
- package/assets/skills/converted/claude-api/composable/presets/go.md +1598 -0
- package/assets/skills/converted/claude-api/composable/presets/java.md +1523 -0
- package/assets/skills/converted/claude-api/composable/presets/php.md +1488 -0
- package/assets/skills/converted/claude-api/composable/presets/python.md +2605 -0
- package/assets/skills/converted/claude-api/composable/presets/ruby.md +1146 -0
- package/assets/skills/converted/claude-api/composable/presets/shared.md +6478 -0
- package/assets/skills/converted/claude-api/composable/presets/typescript.md +2261 -0
- package/assets/skills/converted/docx/composable/BUNDLE.md +617 -0
- package/assets/skills/converted/docx/composable/INDEX.md +12 -0
- package/assets/skills/converted/docx/composable/VERSION +1 -0
- package/assets/skills/converted/docx/composable/mini/00-core.md +26 -0
- package/assets/skills/converted/docx/composable/mini/01-reading-converting.md +36 -0
- package/assets/skills/converted/docx/composable/mini/02-creating-setup-layout.md +85 -0
- package/assets/skills/converted/docx/composable/mini/03-creating-elements.md +257 -0
- package/assets/skills/converted/docx/composable/mini/04-editing-existing.md +57 -0
- package/assets/skills/converted/docx/composable/mini/05-xml-reference.md +128 -0
- package/assets/skills/converted/internal-comms/composable/BUNDLE.md +220 -0
- package/assets/skills/converted/internal-comms/composable/INDEX.md +11 -0
- package/assets/skills/converted/internal-comms/composable/VERSION +1 -0
- package/assets/skills/converted/internal-comms/composable/mini/00-core.md +30 -0
- package/assets/skills/converted/internal-comms/composable/mini/01-3p-updates.md +49 -0
- package/assets/skills/converted/internal-comms/composable/mini/02-company-newsletter.md +67 -0
- package/assets/skills/converted/internal-comms/composable/mini/03-faq-answers.md +32 -0
- package/assets/skills/converted/internal-comms/composable/mini/04-general-comms.md +18 -0
- package/assets/skills/converted/mcp-builder/composable/BUNDLE.md +2460 -0
- package/assets/skills/converted/mcp-builder/composable/INDEX.md +23 -0
- package/assets/skills/converted/mcp-builder/composable/VERSION +1 -0
- package/assets/skills/converted/mcp-builder/composable/mini/00-core.md +43 -0
- package/assets/skills/converted/mcp-builder/composable/mini/01-workflow-research-planning.md +54 -0
- package/assets/skills/converted/mcp-builder/composable/mini/02-implementation-process.md +78 -0
- package/assets/skills/converted/mcp-builder/composable/mini/03-naming-conventions.md +33 -0
- package/assets/skills/converted/mcp-builder/composable/mini/04-response-formats.md +21 -0
- package/assets/skills/converted/mcp-builder/composable/mini/05-pagination.md +24 -0
- package/assets/skills/converted/mcp-builder/composable/mini/06-transport.md +47 -0
- package/assets/skills/converted/mcp-builder/composable/mini/07-annotations.md +20 -0
- package/assets/skills/converted/mcp-builder/composable/mini/08-security.md +35 -0
- package/assets/skills/converted/mcp-builder/composable/mini/09-error-handling.md +32 -0
- package/assets/skills/converted/mcp-builder/composable/mini/10-testing-and-documentation.md +21 -0
- package/assets/skills/converted/mcp-builder/composable/mini/11-python-implementation.md +432 -0
- package/assets/skills/converted/mcp-builder/composable/mini/12-python-advanced-and-checklist.md +233 -0
- package/assets/skills/converted/mcp-builder/composable/mini/13-node-implementation.md +717 -0
- package/assets/skills/converted/mcp-builder/composable/mini/14-node-advanced-and-checklist.md +200 -0
- package/assets/skills/converted/mcp-builder/composable/mini/15-evaluation-design.md +200 -0
- package/assets/skills/converted/mcp-builder/composable/mini/16-evaluation-running.md +198 -0
- package/assets/skills/converted/mcp-builder/composable/presets/node-server.md +1381 -0
- package/assets/skills/converted/mcp-builder/composable/presets/python-server.md +1129 -0
- package/assets/skills/converted/pdf/composable/BUNDLE.md +1284 -0
- package/assets/skills/converted/pdf/composable/INDEX.md +14 -0
- package/assets/skills/converted/pdf/composable/VERSION +1 -0
- package/assets/skills/converted/pdf/composable/mini/00-core.md +46 -0
- package/assets/skills/converted/pdf/composable/mini/01-creation.md +176 -0
- package/assets/skills/converted/pdf/composable/mini/02-extraction.md +178 -0
- package/assets/skills/converted/pdf/composable/mini/03-merge-split-manipulate.md +240 -0
- package/assets/skills/converted/pdf/composable/mini/04-images-ocr.md +168 -0
- package/assets/skills/converted/pdf/composable/mini/05-encryption.md +51 -0
- package/assets/skills/converted/pdf/composable/mini/06-forms.md +300 -0
- package/assets/skills/converted/pdf/composable/mini/07-libraries-reference.md +89 -0
- package/assets/skills/converted/pptx/composable/BUNDLE.md +911 -0
- package/assets/skills/converted/pptx/composable/INDEX.md +12 -0
- package/assets/skills/converted/pptx/composable/VERSION +1 -0
- package/assets/skills/converted/pptx/composable/mini/00-core.md +37 -0
- package/assets/skills/converted/pptx/composable/mini/01-reading.md +37 -0
- package/assets/skills/converted/pptx/composable/mini/02-creating-from-scratch.md +422 -0
- package/assets/skills/converted/pptx/composable/mini/03-editing-templates.md +207 -0
- package/assets/skills/converted/pptx/composable/mini/04-design.md +89 -0
- package/assets/skills/converted/pptx/composable/mini/05-qa-and-rendering.md +91 -0
- package/assets/skills/converted/pptx/composable/presets/creating.md +659 -0
- package/assets/skills/converted/pptx/composable/presets/editing.md +485 -0
- package/assets/skills/converted/skill-creator/composable/BUNDLE.md +1681 -0
- package/assets/skills/converted/skill-creator/composable/INDEX.md +21 -0
- package/assets/skills/converted/skill-creator/composable/VERSION +1 -0
- package/assets/skills/converted/skill-creator/composable/mini/00-core.md +59 -0
- package/assets/skills/converted/skill-creator/composable/mini/01-creating-a-skill.md +27 -0
- package/assets/skills/converted/skill-creator/composable/mini/02-skill-writing-guide.md +71 -0
- package/assets/skills/converted/skill-creator/composable/mini/03-test-cases.md +21 -0
- package/assets/skills/converted/skill-creator/composable/mini/04-running-and-evaluating.md +128 -0
- package/assets/skills/converted/skill-creator/composable/mini/05-improving-the-skill.md +30 -0
- package/assets/skills/converted/skill-creator/composable/mini/06-blind-comparison.md +5 -0
- package/assets/skills/converted/skill-creator/composable/mini/07-description-optimization.md +74 -0
- package/assets/skills/converted/skill-creator/composable/mini/08-packaging.md +11 -0
- package/assets/skills/converted/skill-creator/composable/mini/09-environment-specific.md +38 -0
- package/assets/skills/converted/skill-creator/composable/mini/10-scripts-and-references.md +34 -0
- package/assets/skills/converted/skill-creator/composable/mini/11-json-schemas.md +414 -0
- package/assets/skills/converted/skill-creator/composable/mini/12-agent-grader.md +225 -0
- package/assets/skills/converted/skill-creator/composable/mini/13-agent-comparator.md +204 -0
- package/assets/skills/converted/skill-creator/composable/mini/14-agent-analyzer.md +276 -0
- package/assets/skills/converted/skill-creator/composable/presets/authoring.md +198 -0
- package/assets/skills/converted/skill-creator/composable/presets/evaluating.md +1334 -0
- package/assets/skills/converted/skill-creator/composable/presets/optimizing.md +160 -0
- package/assets/skills/converted/skill-creator/composable/presets.json +5 -0
- package/assets/skills/meta/ccs-skill-creator/composable/BUNDLE.md +465 -0
- package/assets/skills/meta/ccs-skill-creator/composable/INDEX.md +8 -0
- package/assets/skills/meta/ccs-skill-creator/composable/VERSION +1 -0
- package/assets/skills/meta/ccs-skill-creator/composable/mini/00-core.md +46 -0
- package/assets/skills/meta/ccs-skill-creator/composable/mini/01-create-new-skill.md +167 -0
- package/assets/skills/meta/ccs-skill-creator/composable/mini/02-convert-existing-skill.md +120 -0
- package/assets/skills/meta/ccs-skill-creator/composable/mini/03-review-and-maintain.md +112 -0
- package/assets/skills/sources/anthropic/PROVENANCE.md +3 -0
- package/assets/skills/sources/anthropic/claude-api/LICENSE.txt +202 -0
- package/assets/skills/sources/anthropic/docx/LICENSE.txt +30 -0
- package/assets/skills/sources/anthropic/internal-comms/LICENSE.txt +202 -0
- package/assets/skills/sources/anthropic/mcp-builder/LICENSE.txt +202 -0
- package/assets/skills/sources/anthropic/pdf/LICENSE.txt +30 -0
- package/assets/skills/sources/anthropic/pptx/LICENSE.txt +30 -0
- package/assets/skills/sources/anthropic/skill-creator/LICENSE.txt +202 -0
- package/assets/skills/sources/financial-analyst/PROVENANCE.md +1 -0
- package/assets/tools/hive.py +728 -0
- package/dist/cli.js +7494 -0
- package/package.json +40 -0
|
@@ -0,0 +1,1129 @@
|
|
|
1
|
+
<!-- GENERATED by tools/hive.py compile — do not hand-edit. -->
|
|
2
|
+
# mcp-builder — Compiled Skill Bundle — Preset: python-server (v1.0.0)
|
|
3
|
+
|
|
4
|
+
All composable mini-skills for `mcp-builder` concatenated in index order, frontmatter stripped. Regenerate with `tools/hive.py compile <skill-dir>` — do not edit by hand.
|
|
5
|
+
|
|
6
|
+
---
|
|
7
|
+
<!-- module: 00-core.md -->
|
|
8
|
+
|
|
9
|
+
# Core: MCP Server Quality Mindset
|
|
10
|
+
|
|
11
|
+
Always-loaded foundation for building high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Load the focused minis (see INDEX) for the workflow, per-standard rules, language-specific code, and evaluations.
|
|
12
|
+
|
|
13
|
+
## What "quality" means here
|
|
14
|
+
|
|
15
|
+
Create MCP 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** — NOT by how well or comprehensively the server implements tools. Quality is about how the implementations (input/output schemas, docstrings/descriptions, functionality) enable an LLM, with no other context and access ONLY to the MCP server, to answer realistic and difficult questions and complete real tasks.
|
|
16
|
+
|
|
17
|
+
## Agent-first tool design (design for the LLM that will call the tools)
|
|
18
|
+
|
|
19
|
+
- **API coverage vs. workflow tools:** Balance comprehensive API endpoint coverage with specialized workflow tools. Workflow tools can be more convenient for specific tasks; comprehensive coverage gives agents flexibility to compose operations. Performance varies by client — some clients benefit from code execution that combines basic tools, others work better with higher-level workflows. **When uncertain, prioritize comprehensive API coverage.**
|
|
20
|
+
- **Tool naming and discoverability:** Clear, 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. (Full naming rules: see the naming mini.)
|
|
21
|
+
- **Tools should enable complete workflows, not just wrap API endpoints.** Tool names should reflect natural task subdivisions.
|
|
22
|
+
- **Keep tool operations focused and atomic.**
|
|
23
|
+
|
|
24
|
+
## Token-consciousness (context is scarce)
|
|
25
|
+
|
|
26
|
+
- Agents benefit from **concise tool descriptions** and the ability to **filter/paginate** results. Design tools that return **focused, relevant data**.
|
|
27
|
+
- **Response formats should optimize for agent context efficiency.** Omit verbose metadata; return only what the task needs. Some clients support code execution which can help agents filter and process data efficiently.
|
|
28
|
+
- Prefer **human-readable identifiers** where appropriate (display names with IDs, human-readable datetimes) so the agent doesn't waste effort decoding opaque values.
|
|
29
|
+
- Tools that return large JSON objects or lists can overwhelm the LLM — reduce information returned, paginate, and truncate with clear messages.
|
|
30
|
+
|
|
31
|
+
## Error-message discipline
|
|
32
|
+
|
|
33
|
+
- **Error messages must guide agents toward solutions** with specific suggestions and next steps — clear, actionable, and educational. An error should tell the agent what to do next (e.g., suggest a filter to reduce results, or the correct alternative tool).
|
|
34
|
+
- Descriptions must **precisely and unambiguously match actual functionality** — never over- or under-claim what a tool does.
|
|
35
|
+
|
|
36
|
+
## Composability / DRY (applies to every implementation)
|
|
37
|
+
|
|
38
|
+
Your implementation MUST prioritize composability and code reuse:
|
|
39
|
+
|
|
40
|
+
1. **Extract common functionality:** reusable helper functions for operations used across multiple tools; shared API clients for HTTP requests; centralized error-handling logic; business logic in dedicated composable functions; shared markdown/JSON field-selection & formatting.
|
|
41
|
+
2. **Avoid duplication:** NEVER copy-paste similar code between tools. If you write similar logic twice, extract it into a function. Common operations (pagination, filtering, field selection, formatting) should be shared. Authentication/authorization logic should be centralized.
|
|
42
|
+
|
|
43
|
+
## Strategic design checklist (cross-cutting — verify on every server)
|
|
44
|
+
|
|
45
|
+
- [ ] Tools enable complete workflows, not just API endpoint wrappers
|
|
46
|
+
- [ ] Tool names reflect natural task subdivisions
|
|
47
|
+
- [ ] Response formats optimize for agent context efficiency
|
|
48
|
+
- [ ] Human-readable identifiers used where appropriate
|
|
49
|
+
- [ ] Error messages guide agents toward correct usage
|
|
50
|
+
|
|
51
|
+
(Language-specific implementation and code-quality checklists live in the Python and Node minis.)
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
<!-- module: 01-workflow-research-planning.md -->
|
|
55
|
+
|
|
56
|
+
# Workflow, Research & Planning (Phase 1)
|
|
57
|
+
|
|
58
|
+
Creating a high-quality MCP server involves **four main phases**: (1) Deep Research and Planning, (2) Implementation, (3) Review and Test, (4) Create Evaluations. This mini covers Phase 1 and how to navigate the reference documentation.
|
|
59
|
+
|
|
60
|
+
## Phase 1: Deep Research and Planning
|
|
61
|
+
|
|
62
|
+
### 1.1 Understand modern MCP design
|
|
63
|
+
|
|
64
|
+
The core design tensions (agent-first design, API coverage vs. workflow tools, naming/discoverability, context management, actionable errors) are covered in `00-core.md`. Internalize those before designing tools.
|
|
65
|
+
|
|
66
|
+
### 1.2 Study MCP protocol documentation
|
|
67
|
+
|
|
68
|
+
Navigate the MCP specification:
|
|
69
|
+
- Start with the sitemap to find relevant pages: `https://modelcontextprotocol.io/sitemap.xml`
|
|
70
|
+
- Then fetch specific pages with a `.md` suffix for markdown format (e.g., `https://modelcontextprotocol.io/specification/draft.md`).
|
|
71
|
+
|
|
72
|
+
Key pages to review:
|
|
73
|
+
- Specification overview and architecture
|
|
74
|
+
- Transport mechanisms (streamable HTTP, stdio)
|
|
75
|
+
- Tool, resource, and prompt definitions
|
|
76
|
+
|
|
77
|
+
### 1.3 Study framework documentation
|
|
78
|
+
|
|
79
|
+
**Recommended stack:**
|
|
80
|
+
- **Language: TypeScript** — high-quality SDK support and good compatibility in many execution environments (e.g. MCPB). AI models are good at generating TypeScript code, benefiting from its broad usage, static typing, and good linting tools.
|
|
81
|
+
- **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.
|
|
82
|
+
|
|
83
|
+
**Load framework documentation:**
|
|
84
|
+
- **MCP Best Practices** — core universal guidelines (see the naming, response-format, pagination, transport, security, annotations, error-handling, and testing minis).
|
|
85
|
+
- **For TypeScript (recommended):** Use WebFetch to load the TypeScript SDK README: `https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/main/README.md`. Then use the Node/TypeScript implementation minis.
|
|
86
|
+
- **For Python:** Use WebFetch to load the Python SDK README: `https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.md`. Then use the Python implementation minis.
|
|
87
|
+
|
|
88
|
+
### 1.4 Plan your implementation
|
|
89
|
+
|
|
90
|
+
- **Understand the API:** Review the service's API documentation to identify key endpoints, authentication requirements, and data models. Use web search and WebFetch as needed.
|
|
91
|
+
- **Tool selection:** Prioritize comprehensive API coverage. List the endpoints to implement, starting with the most common operations.
|
|
92
|
+
|
|
93
|
+
## Documentation library — what to load and when
|
|
94
|
+
|
|
95
|
+
**Core MCP documentation (load first):**
|
|
96
|
+
- MCP Protocol: start with the sitemap at `https://modelcontextprotocol.io/sitemap.xml`, then fetch specific pages with `.md` suffix.
|
|
97
|
+
- MCP Best Practices — universal guidelines including server/tool naming conventions, response format (JSON vs Markdown), pagination, transport selection (streamable HTTP vs stdio), security, and error handling.
|
|
98
|
+
|
|
99
|
+
**SDK documentation (load during Phase 1/2):**
|
|
100
|
+
- Python SDK: `https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.md`
|
|
101
|
+
- TypeScript SDK: `https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/main/README.md`
|
|
102
|
+
|
|
103
|
+
**Language-specific implementation guides (load during Phase 2):**
|
|
104
|
+
- Python (FastMCP): server initialization, Pydantic models, tool registration with `@mcp.tool`, complete working examples, quality checklist.
|
|
105
|
+
- TypeScript: project structure, Zod schema patterns, tool registration with `server.registerTool`, complete working examples, quality checklist.
|
|
106
|
+
|
|
107
|
+
**Evaluation guide (load during Phase 4):** question creation guidelines, answer verification strategies, XML format, example questions/answers, and running an evaluation with the provided scripts.
|
|
108
|
+
|
|
109
|
+
The remaining phases: Phase 2 (Implementation) and Phase 3 (Review and Test) — see `02-implementation-process.md`. Phase 4 (Create Evaluations) — see the evaluation minis.
|
|
110
|
+
|
|
111
|
+
---
|
|
112
|
+
<!-- module: 02-implementation-process.md -->
|
|
113
|
+
|
|
114
|
+
# Implementation & Review Process (Phases 2–3)
|
|
115
|
+
|
|
116
|
+
Language-agnostic steps for building and then reviewing/testing the server. Use alongside the language-specific minis (Python or Node) for the actual code.
|
|
117
|
+
|
|
118
|
+
## Phase 2: Implementation
|
|
119
|
+
|
|
120
|
+
### 2.1 Set up project structure
|
|
121
|
+
|
|
122
|
+
See the language-specific minis for project setup:
|
|
123
|
+
- TypeScript: project structure, `package.json`, `tsconfig.json`.
|
|
124
|
+
- Python: module organization, dependencies.
|
|
125
|
+
|
|
126
|
+
### 2.2 Implement core infrastructure
|
|
127
|
+
|
|
128
|
+
Create shared utilities:
|
|
129
|
+
- API client with authentication
|
|
130
|
+
- Error handling helpers
|
|
131
|
+
- Response formatting (JSON/Markdown)
|
|
132
|
+
- Pagination support
|
|
133
|
+
|
|
134
|
+
### 2.3 Implement tools
|
|
135
|
+
|
|
136
|
+
For each tool:
|
|
137
|
+
|
|
138
|
+
**Input schema:**
|
|
139
|
+
- Use Zod (TypeScript) or Pydantic (Python)
|
|
140
|
+
- Include constraints and clear descriptions
|
|
141
|
+
- Add examples in field descriptions
|
|
142
|
+
|
|
143
|
+
**Output schema:**
|
|
144
|
+
- Define `outputSchema` where possible for structured data
|
|
145
|
+
- Use `structuredContent` in tool responses (TypeScript SDK feature)
|
|
146
|
+
- Helps clients understand and process tool outputs
|
|
147
|
+
|
|
148
|
+
**Tool description:**
|
|
149
|
+
- Concise summary of functionality
|
|
150
|
+
- Parameter descriptions
|
|
151
|
+
- Return type schema
|
|
152
|
+
|
|
153
|
+
**Implementation:**
|
|
154
|
+
- Async/await for I/O operations
|
|
155
|
+
- Proper error handling with actionable messages
|
|
156
|
+
- Support pagination where applicable
|
|
157
|
+
- Return both text content and structured data when using modern SDKs
|
|
158
|
+
|
|
159
|
+
**Annotations:**
|
|
160
|
+
- `readOnlyHint`: true/false
|
|
161
|
+
- `destructiveHint`: true/false
|
|
162
|
+
- `idempotentHint`: true/false
|
|
163
|
+
- `openWorldHint`: true/false
|
|
164
|
+
|
|
165
|
+
(Full annotation semantics: see the annotations mini.)
|
|
166
|
+
|
|
167
|
+
## Phase 3: Review and Test
|
|
168
|
+
|
|
169
|
+
### 3.1 Code quality
|
|
170
|
+
|
|
171
|
+
Review for:
|
|
172
|
+
- No duplicated code (DRY principle)
|
|
173
|
+
- Consistent error handling
|
|
174
|
+
- Full type coverage
|
|
175
|
+
- Clear tool descriptions
|
|
176
|
+
|
|
177
|
+
### 3.2 Build and test
|
|
178
|
+
|
|
179
|
+
**TypeScript:**
|
|
180
|
+
- Run `npm run build` to verify compilation
|
|
181
|
+
- Test with MCP Inspector: `npx @modelcontextprotocol/inspector`
|
|
182
|
+
|
|
183
|
+
**Python:**
|
|
184
|
+
- Verify syntax: `python -m py_compile your_server.py`
|
|
185
|
+
- Test with MCP Inspector
|
|
186
|
+
|
|
187
|
+
See the language-specific minis for detailed testing approaches and quality checklists.
|
|
188
|
+
|
|
189
|
+
## Phase 4: Create Evaluations
|
|
190
|
+
|
|
191
|
+
After implementing your MCP server, create comprehensive evaluations to test its effectiveness. Use evaluations to test whether LLMs can effectively use your MCP server to answer realistic, complex questions. The process (10 questions: tool inspection → content exploration → question generation → answer verification) and the harness for running them are covered in the evaluation minis.
|
|
192
|
+
|
|
193
|
+
---
|
|
194
|
+
<!-- module: 03-naming-conventions.md -->
|
|
195
|
+
|
|
196
|
+
# Naming Conventions (Server & Tools)
|
|
197
|
+
|
|
198
|
+
## Server naming
|
|
199
|
+
|
|
200
|
+
Follow these standardized naming patterns:
|
|
201
|
+
|
|
202
|
+
- **Python:** `{service}_mcp` (lowercase with underscores) — e.g., `slack_mcp`, `github_mcp`, `jira_mcp`, `stripe_mcp`.
|
|
203
|
+
- **Node/TypeScript:** `{service}-mcp-server` (lowercase with hyphens) — e.g., `slack-mcp-server`, `github-mcp-server`, `jira-mcp-server`, `stripe-mcp-server`.
|
|
204
|
+
|
|
205
|
+
The name should be:
|
|
206
|
+
- **General** — descriptive of the service being integrated, not tied to specific features.
|
|
207
|
+
- **Descriptive** of the service/API being integrated.
|
|
208
|
+
- **Easy to infer** from the task description.
|
|
209
|
+
- **Without version numbers** or dates.
|
|
210
|
+
|
|
211
|
+
## Tool naming
|
|
212
|
+
|
|
213
|
+
1. **Use snake_case:** `search_users`, `create_project`, `get_channel_info`.
|
|
214
|
+
2. **Include service prefix** — anticipate that your MCP server may be used alongside other MCP servers, so include the service context to prevent overlaps:
|
|
215
|
+
- Use `slack_send_message` instead of just `send_message`
|
|
216
|
+
- Use `github_create_issue` instead of just `create_issue`
|
|
217
|
+
- Use `asana_list_tasks` instead of just `list_tasks`
|
|
218
|
+
3. **Be action-oriented:** start with verbs (get, list, search, create, etc.).
|
|
219
|
+
4. **Be specific:** avoid generic names that could conflict with other servers.
|
|
220
|
+
|
|
221
|
+
Format: `{service}_{action}_{resource}` — e.g., `slack_send_message`, `github_create_issue`.
|
|
222
|
+
|
|
223
|
+
## Tool design
|
|
224
|
+
|
|
225
|
+
- Tool descriptions must **narrowly and unambiguously** describe functionality.
|
|
226
|
+
- Descriptions must **precisely match actual functionality**.
|
|
227
|
+
- Provide tool annotations (`readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`) — see the annotations mini.
|
|
228
|
+
- Keep tool operations **focused and atomic**.
|
|
229
|
+
|
|
230
|
+
---
|
|
231
|
+
<!-- module: 04-response-formats.md -->
|
|
232
|
+
|
|
233
|
+
# Response Formats (JSON vs Markdown)
|
|
234
|
+
|
|
235
|
+
All tools that return data should support **multiple formats**, typically via a `response_format` parameter that defaults to markdown. JSON is for programmatic processing; Markdown is for human readability.
|
|
236
|
+
|
|
237
|
+
## JSON format (`response_format="json"`)
|
|
238
|
+
|
|
239
|
+
- Machine-readable structured data
|
|
240
|
+
- Return complete, structured data suitable for programmatic processing
|
|
241
|
+
- Include all available fields and metadata
|
|
242
|
+
- Use consistent field names and types
|
|
243
|
+
|
|
244
|
+
## Markdown format (`response_format="markdown"`, typically the default)
|
|
245
|
+
|
|
246
|
+
- Human-readable formatted text
|
|
247
|
+
- Use headers, lists, and formatting for clarity
|
|
248
|
+
- Convert timestamps to human-readable format (e.g., "2024-01-15 10:30:00 UTC" instead of epoch)
|
|
249
|
+
- Show display names with IDs in parentheses (e.g., "@john.doe (U123456)")
|
|
250
|
+
- Omit verbose metadata (e.g., show only one profile image URL, not all sizes)
|
|
251
|
+
- Group related information logically
|
|
252
|
+
|
|
253
|
+
(Language-specific code for implementing the `ResponseFormat` enum and formatting both branches lives in the Python and Node minis.)
|
|
254
|
+
|
|
255
|
+
---
|
|
256
|
+
<!-- module: 05-pagination.md -->
|
|
257
|
+
|
|
258
|
+
# Pagination
|
|
259
|
+
|
|
260
|
+
For tools that list resources:
|
|
261
|
+
|
|
262
|
+
- **Always respect the `limit` parameter.**
|
|
263
|
+
- **Implement pagination:** use `offset` or cursor-based pagination.
|
|
264
|
+
- **Return pagination metadata:** include `has_more`, `next_offset`/`next_cursor`, and `total_count`.
|
|
265
|
+
- **Never load all results into memory** — especially important for large datasets.
|
|
266
|
+
- **Default to reasonable limits:** 20–50 items is typical.
|
|
267
|
+
|
|
268
|
+
Example pagination response:
|
|
269
|
+
|
|
270
|
+
```json
|
|
271
|
+
{
|
|
272
|
+
"total": 150,
|
|
273
|
+
"count": 20,
|
|
274
|
+
"offset": 0,
|
|
275
|
+
"items": [...],
|
|
276
|
+
"has_more": true,
|
|
277
|
+
"next_offset": 20
|
|
278
|
+
}
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
(Language-specific pagination code — computing `has_more` and `next_offset` from `total`, `offset`, and returned items — lives in the Python and Node minis.)
|
|
282
|
+
|
|
283
|
+
---
|
|
284
|
+
<!-- module: 06-transport.md -->
|
|
285
|
+
|
|
286
|
+
# Transport Options
|
|
287
|
+
|
|
288
|
+
Two main transports: **Streamable HTTP** (remote) and **stdio** (local). **Avoid SSE — deprecated in favor of streamable HTTP.**
|
|
289
|
+
|
|
290
|
+
## Streamable HTTP
|
|
291
|
+
|
|
292
|
+
**Best for:** remote servers, web services, multi-client scenarios.
|
|
293
|
+
|
|
294
|
+
**Characteristics:**
|
|
295
|
+
- Bidirectional communication over HTTP
|
|
296
|
+
- Supports multiple simultaneous clients
|
|
297
|
+
- Can be deployed as a web service
|
|
298
|
+
- Enables server-to-client notifications
|
|
299
|
+
|
|
300
|
+
**Use when:**
|
|
301
|
+
- Serving multiple clients simultaneously
|
|
302
|
+
- Deploying as a cloud service
|
|
303
|
+
- Integrating with web applications
|
|
304
|
+
|
|
305
|
+
For remote servers, prefer **stateless JSON** (simpler to scale and maintain than stateful sessions and streaming responses).
|
|
306
|
+
|
|
307
|
+
## stdio
|
|
308
|
+
|
|
309
|
+
**Best for:** local integrations, command-line tools.
|
|
310
|
+
|
|
311
|
+
**Characteristics:**
|
|
312
|
+
- Standard input/output stream communication
|
|
313
|
+
- Simple setup, no network configuration needed
|
|
314
|
+
- Runs as a subprocess of the client
|
|
315
|
+
|
|
316
|
+
**Use when:**
|
|
317
|
+
- Building tools for local development environments
|
|
318
|
+
- Integrating with desktop applications
|
|
319
|
+
- Single-user, single-session scenarios
|
|
320
|
+
|
|
321
|
+
**Note:** stdio servers must NOT log to stdout — use stderr for logging.
|
|
322
|
+
|
|
323
|
+
## Transport selection
|
|
324
|
+
|
|
325
|
+
| Criterion | stdio | Streamable HTTP |
|
|
326
|
+
|-----------|-------|-----------------|
|
|
327
|
+
| **Deployment** | Local | Remote |
|
|
328
|
+
| **Clients** | Single | Multiple |
|
|
329
|
+
| **Complexity** | Low | Medium |
|
|
330
|
+
| **Real-time** | No | Yes |
|
|
331
|
+
|
|
332
|
+
(Language-specific code for wiring up each transport lives in the Python and Node minis.)
|
|
333
|
+
|
|
334
|
+
---
|
|
335
|
+
<!-- module: 07-annotations.md -->
|
|
336
|
+
|
|
337
|
+
# Tool Annotations
|
|
338
|
+
|
|
339
|
+
Provide annotations to help clients understand tool behavior. Set them on every tool.
|
|
340
|
+
|
|
341
|
+
| Annotation | Type | Default | Description |
|
|
342
|
+
|-----------|------|---------|-------------|
|
|
343
|
+
| `readOnlyHint` | boolean | false | Tool does not modify its environment |
|
|
344
|
+
| `destructiveHint` | boolean | true | Tool may perform destructive updates |
|
|
345
|
+
| `idempotentHint` | boolean | false | Repeated calls with same args have no additional effect |
|
|
346
|
+
| `openWorldHint` | boolean | true | Tool interacts with external entities |
|
|
347
|
+
|
|
348
|
+
**Important:** Annotations are **hints, not security guarantees**. Clients should not make security-critical decisions based solely on annotations.
|
|
349
|
+
|
|
350
|
+
Set each hint to accurately reflect the tool:
|
|
351
|
+
- `readOnlyHint`: true if the tool does not modify environment
|
|
352
|
+
- `destructiveHint`: false if the tool does not perform destructive operations
|
|
353
|
+
- `idempotentHint`: true if repeated calls have no additional effect
|
|
354
|
+
- `openWorldHint`: false if the tool does not interact with external entities
|
|
355
|
+
|
|
356
|
+
(Language-specific syntax — the `annotations={...}` dict in the `@mcp.tool` decorator for Python, and the `annotations` object in `registerTool` for Node — lives in the language minis.)
|
|
357
|
+
|
|
358
|
+
---
|
|
359
|
+
<!-- module: 08-security.md -->
|
|
360
|
+
|
|
361
|
+
# Security Best Practices
|
|
362
|
+
|
|
363
|
+
## Authentication and Authorization
|
|
364
|
+
|
|
365
|
+
**OAuth 2.1:**
|
|
366
|
+
- Use secure OAuth 2.1 with certificates from recognized authorities
|
|
367
|
+
- Validate access tokens before processing requests
|
|
368
|
+
- Only accept tokens specifically intended for your server
|
|
369
|
+
|
|
370
|
+
**API Keys:**
|
|
371
|
+
- Store API keys in environment variables, never in code
|
|
372
|
+
- Validate keys on server startup
|
|
373
|
+
- Provide clear error messages when authentication fails
|
|
374
|
+
|
|
375
|
+
## Input Validation
|
|
376
|
+
|
|
377
|
+
- Sanitize file paths to prevent directory traversal
|
|
378
|
+
- Validate URLs and external identifiers
|
|
379
|
+
- Check parameter sizes and ranges
|
|
380
|
+
- Prevent command injection in system calls
|
|
381
|
+
- Use schema validation (Pydantic/Zod) for all inputs
|
|
382
|
+
|
|
383
|
+
## Error Handling (security angle)
|
|
384
|
+
|
|
385
|
+
- Don't expose internal errors to clients
|
|
386
|
+
- Log security-relevant errors server-side
|
|
387
|
+
- Provide helpful but not revealing error messages
|
|
388
|
+
- Clean up resources after errors
|
|
389
|
+
|
|
390
|
+
## DNS Rebinding Protection
|
|
391
|
+
|
|
392
|
+
For streamable HTTP servers running locally:
|
|
393
|
+
- Enable DNS rebinding protection
|
|
394
|
+
- Validate the `Origin` header on all incoming connections
|
|
395
|
+
- Bind to `127.0.0.1` rather than `0.0.0.0`
|
|
396
|
+
|
|
397
|
+
---
|
|
398
|
+
<!-- module: 09-error-handling.md -->
|
|
399
|
+
|
|
400
|
+
# Error Handling Standards
|
|
401
|
+
|
|
402
|
+
General, cross-language error-handling standards. Language-specific error formatting (`_handle_api_error` in Python, `handleApiError` in Node, mapping 404/403/429/timeout to messages) lives in the language minis.
|
|
403
|
+
|
|
404
|
+
## Principles
|
|
405
|
+
|
|
406
|
+
- Use standard **JSON-RPC error codes**.
|
|
407
|
+
- **Report tool errors within result objects** (not protocol-level errors).
|
|
408
|
+
- Provide **helpful, specific error messages with suggested next steps**.
|
|
409
|
+
- **Don't expose internal implementation details.**
|
|
410
|
+
- **Clean up resources properly on errors.**
|
|
411
|
+
|
|
412
|
+
Error messages should be clear, actionable, and educational — guiding the agent toward a solution with specific suggestions and next steps.
|
|
413
|
+
|
|
414
|
+
## Example (TypeScript pattern)
|
|
415
|
+
|
|
416
|
+
```typescript
|
|
417
|
+
try {
|
|
418
|
+
const result = performOperation();
|
|
419
|
+
return { content: [{ type: "text", text: result }] };
|
|
420
|
+
} catch (error) {
|
|
421
|
+
return {
|
|
422
|
+
isError: true,
|
|
423
|
+
content: [{
|
|
424
|
+
type: "text",
|
|
425
|
+
text: `Error: ${error.message}. Try using filter='active_only' to reduce results.`
|
|
426
|
+
}]
|
|
427
|
+
};
|
|
428
|
+
}
|
|
429
|
+
```
|
|
430
|
+
|
|
431
|
+
Note how the message not only reports the failure but suggests a concrete next step (`filter='active_only'`) that helps the agent recover.
|
|
432
|
+
|
|
433
|
+
---
|
|
434
|
+
<!-- module: 10-testing-and-documentation.md -->
|
|
435
|
+
|
|
436
|
+
# Testing & Documentation Requirements
|
|
437
|
+
|
|
438
|
+
General (language-agnostic) requirements. Language-specific build/test commands and quality checklists live in the Python and Node minis; the evaluation harness is covered in the evaluation minis.
|
|
439
|
+
|
|
440
|
+
## Testing Requirements
|
|
441
|
+
|
|
442
|
+
Comprehensive testing should cover:
|
|
443
|
+
|
|
444
|
+
- **Functional testing:** verify correct execution with valid/invalid inputs.
|
|
445
|
+
- **Integration testing:** test interaction with external systems.
|
|
446
|
+
- **Security testing:** validate auth, input sanitization, rate limiting.
|
|
447
|
+
- **Performance testing:** check behavior under load, timeouts.
|
|
448
|
+
- **Error handling:** ensure proper error reporting and cleanup.
|
|
449
|
+
|
|
450
|
+
## Documentation Requirements
|
|
451
|
+
|
|
452
|
+
- Provide clear documentation of all tools and capabilities.
|
|
453
|
+
- Include working examples (**at least 3 per major feature**).
|
|
454
|
+
- Document security considerations.
|
|
455
|
+
- Specify required permissions and access levels.
|
|
456
|
+
- Document rate limits and performance characteristics.
|
|
457
|
+
|
|
458
|
+
---
|
|
459
|
+
<!-- module: 11-python-implementation.md -->
|
|
460
|
+
|
|
461
|
+
# Python (FastMCP) — Implementation Patterns
|
|
462
|
+
|
|
463
|
+
Python-specific best practices and code for implementing MCP servers with the MCP Python SDK (FastMCP): server setup, tool registration, input validation with Pydantic, error handling, and a complete working example. Server naming (`{service}_mcp`) and tool naming are in the naming mini; this mini is the how-in-Python.
|
|
464
|
+
|
|
465
|
+
## MCP Python SDK and FastMCP
|
|
466
|
+
|
|
467
|
+
The official MCP Python SDK provides FastMCP, a high-level framework for building MCP servers. It provides:
|
|
468
|
+
- Automatic description and inputSchema generation from function signatures and docstrings
|
|
469
|
+
- Pydantic model integration for input validation
|
|
470
|
+
- Decorator-based tool registration with `@mcp.tool`
|
|
471
|
+
|
|
472
|
+
For complete SDK documentation, use WebFetch to load: `https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.md`
|
|
473
|
+
|
|
474
|
+
## Quick Reference
|
|
475
|
+
|
|
476
|
+
### Key imports
|
|
477
|
+
```python
|
|
478
|
+
from mcp.server.fastmcp import FastMCP
|
|
479
|
+
from pydantic import BaseModel, Field, field_validator, ConfigDict
|
|
480
|
+
from typing import Optional, List, Dict, Any
|
|
481
|
+
from enum import Enum
|
|
482
|
+
import httpx
|
|
483
|
+
```
|
|
484
|
+
|
|
485
|
+
### Server initialization
|
|
486
|
+
```python
|
|
487
|
+
mcp = FastMCP("service_mcp")
|
|
488
|
+
```
|
|
489
|
+
|
|
490
|
+
### Tool registration pattern
|
|
491
|
+
```python
|
|
492
|
+
@mcp.tool(name="tool_name", annotations={...})
|
|
493
|
+
async def tool_function(params: InputModel) -> str:
|
|
494
|
+
# Implementation
|
|
495
|
+
pass
|
|
496
|
+
```
|
|
497
|
+
|
|
498
|
+
## Tool Structure with FastMCP
|
|
499
|
+
|
|
500
|
+
Tools are defined using the `@mcp.tool` decorator with Pydantic models for input validation. Use snake_case, action-oriented tool names with a service prefix (e.g., `slack_send_message`, `github_create_issue`, `asana_list_tasks`).
|
|
501
|
+
|
|
502
|
+
```python
|
|
503
|
+
from pydantic import BaseModel, Field, ConfigDict
|
|
504
|
+
from mcp.server.fastmcp import FastMCP
|
|
505
|
+
|
|
506
|
+
# Initialize the MCP server
|
|
507
|
+
mcp = FastMCP("example_mcp")
|
|
508
|
+
|
|
509
|
+
# Define Pydantic model for input validation
|
|
510
|
+
class ServiceToolInput(BaseModel):
|
|
511
|
+
'''Input model for service tool operation.'''
|
|
512
|
+
model_config = ConfigDict(
|
|
513
|
+
str_strip_whitespace=True, # Auto-strip whitespace from strings
|
|
514
|
+
validate_assignment=True, # Validate on assignment
|
|
515
|
+
extra='forbid' # Forbid extra fields
|
|
516
|
+
)
|
|
517
|
+
|
|
518
|
+
param1: str = Field(..., description="First parameter description (e.g., 'user123', 'project-abc')", min_length=1, max_length=100)
|
|
519
|
+
param2: Optional[int] = Field(default=None, description="Optional integer parameter with constraints", ge=0, le=1000)
|
|
520
|
+
tags: Optional[List[str]] = Field(default_factory=list, description="List of tags to apply", max_items=10)
|
|
521
|
+
|
|
522
|
+
@mcp.tool(
|
|
523
|
+
name="service_tool_name",
|
|
524
|
+
annotations={
|
|
525
|
+
"title": "Human-Readable Tool Title",
|
|
526
|
+
"readOnlyHint": True, # Tool does not modify environment
|
|
527
|
+
"destructiveHint": False, # Tool does not perform destructive operations
|
|
528
|
+
"idempotentHint": True, # Repeated calls have no additional effect
|
|
529
|
+
"openWorldHint": False # Tool does not interact with external entities
|
|
530
|
+
}
|
|
531
|
+
)
|
|
532
|
+
async def service_tool_name(params: ServiceToolInput) -> str:
|
|
533
|
+
'''Tool description automatically becomes the 'description' field.
|
|
534
|
+
|
|
535
|
+
This tool performs a specific operation on the service. It validates all inputs
|
|
536
|
+
using the ServiceToolInput Pydantic model before processing.
|
|
537
|
+
|
|
538
|
+
Args:
|
|
539
|
+
params (ServiceToolInput): Validated input parameters containing:
|
|
540
|
+
- param1 (str): First parameter description
|
|
541
|
+
- param2 (Optional[int]): Optional parameter with default
|
|
542
|
+
- tags (Optional[List[str]]): List of tags
|
|
543
|
+
|
|
544
|
+
Returns:
|
|
545
|
+
str: JSON-formatted response containing operation results
|
|
546
|
+
'''
|
|
547
|
+
# Implementation here
|
|
548
|
+
pass
|
|
549
|
+
```
|
|
550
|
+
|
|
551
|
+
## Pydantic v2 Key Features
|
|
552
|
+
|
|
553
|
+
- Use `model_config` instead of nested `Config` class
|
|
554
|
+
- Use `field_validator` instead of deprecated `validator`
|
|
555
|
+
- Use `model_dump()` instead of deprecated `dict()`
|
|
556
|
+
- Validators require `@classmethod` decorator
|
|
557
|
+
- Type hints are required for validator methods
|
|
558
|
+
|
|
559
|
+
```python
|
|
560
|
+
from pydantic import BaseModel, Field, field_validator, ConfigDict
|
|
561
|
+
|
|
562
|
+
class CreateUserInput(BaseModel):
|
|
563
|
+
model_config = ConfigDict(
|
|
564
|
+
str_strip_whitespace=True,
|
|
565
|
+
validate_assignment=True
|
|
566
|
+
)
|
|
567
|
+
|
|
568
|
+
name: str = Field(..., description="User's full name", min_length=1, max_length=100)
|
|
569
|
+
email: str = Field(..., description="User's email address", pattern=r'^[\w\.-]+@[\w\.-]+\.\w+$')
|
|
570
|
+
age: int = Field(..., description="User's age", ge=0, le=150)
|
|
571
|
+
|
|
572
|
+
@field_validator('email')
|
|
573
|
+
@classmethod
|
|
574
|
+
def validate_email(cls, v: str) -> str:
|
|
575
|
+
if not v.strip():
|
|
576
|
+
raise ValueError("Email cannot be empty")
|
|
577
|
+
return v.lower()
|
|
578
|
+
```
|
|
579
|
+
|
|
580
|
+
## Response Format Options
|
|
581
|
+
|
|
582
|
+
Support multiple output formats for flexibility (concept in the response-formats mini):
|
|
583
|
+
|
|
584
|
+
```python
|
|
585
|
+
from enum import Enum
|
|
586
|
+
|
|
587
|
+
class ResponseFormat(str, Enum):
|
|
588
|
+
'''Output format for tool responses.'''
|
|
589
|
+
MARKDOWN = "markdown"
|
|
590
|
+
JSON = "json"
|
|
591
|
+
|
|
592
|
+
class UserSearchInput(BaseModel):
|
|
593
|
+
query: str = Field(..., description="Search query")
|
|
594
|
+
response_format: ResponseFormat = Field(
|
|
595
|
+
default=ResponseFormat.MARKDOWN,
|
|
596
|
+
description="Output format: 'markdown' for human-readable or 'json' for machine-readable"
|
|
597
|
+
)
|
|
598
|
+
```
|
|
599
|
+
|
|
600
|
+
**Markdown format:** use headers, lists, and formatting for clarity; convert timestamps to human-readable format (e.g., "2024-01-15 10:30:00 UTC" instead of epoch); show display names with IDs in parentheses (e.g., "@john.doe (U123456)"); omit verbose metadata (e.g., show only one profile image URL, not all sizes); group related information logically.
|
|
601
|
+
|
|
602
|
+
**JSON format:** return complete, structured data suitable for programmatic processing; include all available fields and metadata; use consistent field names and types.
|
|
603
|
+
|
|
604
|
+
## Pagination Implementation
|
|
605
|
+
|
|
606
|
+
```python
|
|
607
|
+
class ListInput(BaseModel):
|
|
608
|
+
limit: Optional[int] = Field(default=20, description="Maximum results to return", ge=1, le=100)
|
|
609
|
+
offset: Optional[int] = Field(default=0, description="Number of results to skip for pagination", ge=0)
|
|
610
|
+
|
|
611
|
+
async def list_items(params: ListInput) -> str:
|
|
612
|
+
# Make API request with pagination
|
|
613
|
+
data = await api_request(limit=params.limit, offset=params.offset)
|
|
614
|
+
|
|
615
|
+
# Return pagination info
|
|
616
|
+
response = {
|
|
617
|
+
"total": data["total"],
|
|
618
|
+
"count": len(data["items"]),
|
|
619
|
+
"offset": params.offset,
|
|
620
|
+
"items": data["items"],
|
|
621
|
+
"has_more": data["total"] > params.offset + len(data["items"]),
|
|
622
|
+
"next_offset": params.offset + len(data["items"]) if data["total"] > params.offset + len(data["items"]) else None
|
|
623
|
+
}
|
|
624
|
+
return json.dumps(response, indent=2)
|
|
625
|
+
```
|
|
626
|
+
|
|
627
|
+
## Error Handling
|
|
628
|
+
|
|
629
|
+
Provide clear, actionable error messages:
|
|
630
|
+
|
|
631
|
+
```python
|
|
632
|
+
def _handle_api_error(e: Exception) -> str:
|
|
633
|
+
'''Consistent error formatting across all tools.'''
|
|
634
|
+
if isinstance(e, httpx.HTTPStatusError):
|
|
635
|
+
if e.response.status_code == 404:
|
|
636
|
+
return "Error: Resource not found. Please check the ID is correct."
|
|
637
|
+
elif e.response.status_code == 403:
|
|
638
|
+
return "Error: Permission denied. You don't have access to this resource."
|
|
639
|
+
elif e.response.status_code == 429:
|
|
640
|
+
return "Error: Rate limit exceeded. Please wait before making more requests."
|
|
641
|
+
return f"Error: API request failed with status {e.response.status_code}"
|
|
642
|
+
elif isinstance(e, httpx.TimeoutException):
|
|
643
|
+
return "Error: Request timed out. Please try again."
|
|
644
|
+
return f"Error: Unexpected error occurred: {type(e).__name__}"
|
|
645
|
+
```
|
|
646
|
+
|
|
647
|
+
## Shared Utilities
|
|
648
|
+
|
|
649
|
+
Extract common functionality into reusable functions:
|
|
650
|
+
|
|
651
|
+
```python
|
|
652
|
+
# Shared API request function
|
|
653
|
+
async def _make_api_request(endpoint: str, method: str = "GET", **kwargs) -> dict:
|
|
654
|
+
'''Reusable function for all API calls.'''
|
|
655
|
+
async with httpx.AsyncClient() as client:
|
|
656
|
+
response = await client.request(
|
|
657
|
+
method,
|
|
658
|
+
f"{API_BASE_URL}/{endpoint}",
|
|
659
|
+
timeout=30.0,
|
|
660
|
+
**kwargs
|
|
661
|
+
)
|
|
662
|
+
response.raise_for_status()
|
|
663
|
+
return response.json()
|
|
664
|
+
```
|
|
665
|
+
|
|
666
|
+
## Async/Await Best Practices
|
|
667
|
+
|
|
668
|
+
Always use async/await for network requests and I/O operations:
|
|
669
|
+
|
|
670
|
+
```python
|
|
671
|
+
# Good: Async network request
|
|
672
|
+
async def fetch_data(resource_id: str) -> dict:
|
|
673
|
+
async with httpx.AsyncClient() as client:
|
|
674
|
+
response = await client.get(f"{API_URL}/resource/{resource_id}")
|
|
675
|
+
response.raise_for_status()
|
|
676
|
+
return response.json()
|
|
677
|
+
|
|
678
|
+
# Bad: Synchronous request
|
|
679
|
+
def fetch_data(resource_id: str) -> dict:
|
|
680
|
+
response = requests.get(f"{API_URL}/resource/{resource_id}") # Blocks
|
|
681
|
+
return response.json()
|
|
682
|
+
```
|
|
683
|
+
|
|
684
|
+
## Type Hints
|
|
685
|
+
|
|
686
|
+
Use type hints throughout:
|
|
687
|
+
|
|
688
|
+
```python
|
|
689
|
+
from typing import Optional, List, Dict, Any
|
|
690
|
+
|
|
691
|
+
async def get_user(user_id: str) -> Dict[str, Any]:
|
|
692
|
+
data = await fetch_user(user_id)
|
|
693
|
+
return {"id": data["id"], "name": data["name"]}
|
|
694
|
+
```
|
|
695
|
+
|
|
696
|
+
## Tool Docstrings
|
|
697
|
+
|
|
698
|
+
Every tool must have comprehensive docstrings with explicit type information, including the complete schema structure for dict/JSON returns and usage examples:
|
|
699
|
+
|
|
700
|
+
```python
|
|
701
|
+
async def search_users(params: UserSearchInput) -> str:
|
|
702
|
+
'''
|
|
703
|
+
Search for users in the Example system by name, email, or team.
|
|
704
|
+
|
|
705
|
+
This tool searches across all user profiles in the Example platform,
|
|
706
|
+
supporting partial matches and various search filters. It does NOT
|
|
707
|
+
create or modify users, only searches existing ones.
|
|
708
|
+
|
|
709
|
+
Args:
|
|
710
|
+
params (UserSearchInput): Validated input parameters containing:
|
|
711
|
+
- query (str): Search string to match against names/emails (e.g., "john", "@example.com", "team:marketing")
|
|
712
|
+
- limit (Optional[int]): Maximum results to return, between 1-100 (default: 20)
|
|
713
|
+
- offset (Optional[int]): Number of results to skip for pagination (default: 0)
|
|
714
|
+
|
|
715
|
+
Returns:
|
|
716
|
+
str: JSON-formatted string containing search results with the following schema:
|
|
717
|
+
|
|
718
|
+
Success response:
|
|
719
|
+
{
|
|
720
|
+
"total": int, # Total number of matches found
|
|
721
|
+
"count": int, # Number of results in this response
|
|
722
|
+
"offset": int, # Current pagination offset
|
|
723
|
+
"users": [
|
|
724
|
+
{
|
|
725
|
+
"id": str, # User ID (e.g., "U123456789")
|
|
726
|
+
"name": str, # Full name (e.g., "John Doe")
|
|
727
|
+
"email": str, # Email address (e.g., "john@example.com")
|
|
728
|
+
"team": str # Team name (e.g., "Marketing") - optional
|
|
729
|
+
}
|
|
730
|
+
]
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
Error response:
|
|
734
|
+
"Error: <error message>" or "No users found matching '<query>'"
|
|
735
|
+
|
|
736
|
+
Examples:
|
|
737
|
+
- Use when: "Find all marketing team members" -> params with query="team:marketing"
|
|
738
|
+
- Use when: "Search for John's account" -> params with query="john"
|
|
739
|
+
- Don't use when: You need to create a user (use example_create_user instead)
|
|
740
|
+
- Don't use when: You have a user ID and need full details (use example_get_user instead)
|
|
741
|
+
|
|
742
|
+
Error Handling:
|
|
743
|
+
- Input validation errors are handled by Pydantic model
|
|
744
|
+
- Returns "Error: Rate limit exceeded" if too many requests (429 status)
|
|
745
|
+
- Returns "Error: Invalid API authentication" if API key is invalid (401 status)
|
|
746
|
+
- Returns formatted list of results or "No users found matching 'query'"
|
|
747
|
+
'''
|
|
748
|
+
```
|
|
749
|
+
|
|
750
|
+
## Complete Example
|
|
751
|
+
|
|
752
|
+
```python
|
|
753
|
+
#!/usr/bin/env python3
|
|
754
|
+
'''
|
|
755
|
+
MCP Server for Example Service.
|
|
756
|
+
|
|
757
|
+
This server provides tools to interact with Example API, including user search,
|
|
758
|
+
project management, and data export capabilities.
|
|
759
|
+
'''
|
|
760
|
+
|
|
761
|
+
from typing import Optional, List, Dict, Any
|
|
762
|
+
from enum import Enum
|
|
763
|
+
import httpx
|
|
764
|
+
from pydantic import BaseModel, Field, field_validator, ConfigDict
|
|
765
|
+
from mcp.server.fastmcp import FastMCP
|
|
766
|
+
|
|
767
|
+
# Initialize the MCP server
|
|
768
|
+
mcp = FastMCP("example_mcp")
|
|
769
|
+
|
|
770
|
+
# Constants
|
|
771
|
+
API_BASE_URL = "https://api.example.com/v1"
|
|
772
|
+
|
|
773
|
+
# Enums
|
|
774
|
+
class ResponseFormat(str, Enum):
|
|
775
|
+
'''Output format for tool responses.'''
|
|
776
|
+
MARKDOWN = "markdown"
|
|
777
|
+
JSON = "json"
|
|
778
|
+
|
|
779
|
+
# Pydantic Models for Input Validation
|
|
780
|
+
class UserSearchInput(BaseModel):
|
|
781
|
+
'''Input model for user search operations.'''
|
|
782
|
+
model_config = ConfigDict(
|
|
783
|
+
str_strip_whitespace=True,
|
|
784
|
+
validate_assignment=True
|
|
785
|
+
)
|
|
786
|
+
|
|
787
|
+
query: str = Field(..., description="Search string to match against names/emails", min_length=2, max_length=200)
|
|
788
|
+
limit: Optional[int] = Field(default=20, description="Maximum results to return", ge=1, le=100)
|
|
789
|
+
offset: Optional[int] = Field(default=0, description="Number of results to skip for pagination", ge=0)
|
|
790
|
+
response_format: ResponseFormat = Field(default=ResponseFormat.MARKDOWN, description="Output format")
|
|
791
|
+
|
|
792
|
+
@field_validator('query')
|
|
793
|
+
@classmethod
|
|
794
|
+
def validate_query(cls, v: str) -> str:
|
|
795
|
+
if not v.strip():
|
|
796
|
+
raise ValueError("Query cannot be empty or whitespace only")
|
|
797
|
+
return v.strip()
|
|
798
|
+
|
|
799
|
+
# Shared utility functions
|
|
800
|
+
async def _make_api_request(endpoint: str, method: str = "GET", **kwargs) -> dict:
|
|
801
|
+
'''Reusable function for all API calls.'''
|
|
802
|
+
async with httpx.AsyncClient() as client:
|
|
803
|
+
response = await client.request(
|
|
804
|
+
method,
|
|
805
|
+
f"{API_BASE_URL}/{endpoint}",
|
|
806
|
+
timeout=30.0,
|
|
807
|
+
**kwargs
|
|
808
|
+
)
|
|
809
|
+
response.raise_for_status()
|
|
810
|
+
return response.json()
|
|
811
|
+
|
|
812
|
+
def _handle_api_error(e: Exception) -> str:
|
|
813
|
+
'''Consistent error formatting across all tools.'''
|
|
814
|
+
if isinstance(e, httpx.HTTPStatusError):
|
|
815
|
+
if e.response.status_code == 404:
|
|
816
|
+
return "Error: Resource not found. Please check the ID is correct."
|
|
817
|
+
elif e.response.status_code == 403:
|
|
818
|
+
return "Error: Permission denied. You don't have access to this resource."
|
|
819
|
+
elif e.response.status_code == 429:
|
|
820
|
+
return "Error: Rate limit exceeded. Please wait before making more requests."
|
|
821
|
+
return f"Error: API request failed with status {e.response.status_code}"
|
|
822
|
+
elif isinstance(e, httpx.TimeoutException):
|
|
823
|
+
return "Error: Request timed out. Please try again."
|
|
824
|
+
return f"Error: Unexpected error occurred: {type(e).__name__}"
|
|
825
|
+
|
|
826
|
+
# Tool definitions
|
|
827
|
+
@mcp.tool(
|
|
828
|
+
name="example_search_users",
|
|
829
|
+
annotations={
|
|
830
|
+
"title": "Search Example Users",
|
|
831
|
+
"readOnlyHint": True,
|
|
832
|
+
"destructiveHint": False,
|
|
833
|
+
"idempotentHint": True,
|
|
834
|
+
"openWorldHint": True
|
|
835
|
+
}
|
|
836
|
+
)
|
|
837
|
+
async def example_search_users(params: UserSearchInput) -> str:
|
|
838
|
+
'''Search for users in the Example system by name, email, or team.
|
|
839
|
+
|
|
840
|
+
[Full docstring as shown above]
|
|
841
|
+
'''
|
|
842
|
+
try:
|
|
843
|
+
# Make API request using validated parameters
|
|
844
|
+
data = await _make_api_request(
|
|
845
|
+
"users/search",
|
|
846
|
+
params={
|
|
847
|
+
"q": params.query,
|
|
848
|
+
"limit": params.limit,
|
|
849
|
+
"offset": params.offset
|
|
850
|
+
}
|
|
851
|
+
)
|
|
852
|
+
|
|
853
|
+
users = data.get("users", [])
|
|
854
|
+
total = data.get("total", 0)
|
|
855
|
+
|
|
856
|
+
if not users:
|
|
857
|
+
return f"No users found matching '{params.query}'"
|
|
858
|
+
|
|
859
|
+
# Format response based on requested format
|
|
860
|
+
if params.response_format == ResponseFormat.MARKDOWN:
|
|
861
|
+
lines = [f"# User Search Results: '{params.query}'", ""]
|
|
862
|
+
lines.append(f"Found {total} users (showing {len(users)})")
|
|
863
|
+
lines.append("")
|
|
864
|
+
|
|
865
|
+
for user in users:
|
|
866
|
+
lines.append(f"## {user['name']} ({user['id']})")
|
|
867
|
+
lines.append(f"- **Email**: {user['email']}")
|
|
868
|
+
if user.get('team'):
|
|
869
|
+
lines.append(f"- **Team**: {user['team']}")
|
|
870
|
+
lines.append("")
|
|
871
|
+
|
|
872
|
+
return "\n".join(lines)
|
|
873
|
+
|
|
874
|
+
else:
|
|
875
|
+
# Machine-readable JSON format
|
|
876
|
+
import json
|
|
877
|
+
response = {
|
|
878
|
+
"total": total,
|
|
879
|
+
"count": len(users),
|
|
880
|
+
"offset": params.offset,
|
|
881
|
+
"users": users
|
|
882
|
+
}
|
|
883
|
+
return json.dumps(response, indent=2)
|
|
884
|
+
|
|
885
|
+
except Exception as e:
|
|
886
|
+
return _handle_api_error(e)
|
|
887
|
+
|
|
888
|
+
if __name__ == "__main__":
|
|
889
|
+
mcp.run()
|
|
890
|
+
```
|
|
891
|
+
|
|
892
|
+
Advanced FastMCP features (context injection, resources, structured output, lifespan, transport), Python-specific best practices, and the quality checklist are in `12-python-advanced-and-checklist.md`.
|
|
893
|
+
|
|
894
|
+
---
|
|
895
|
+
<!-- module: 12-python-advanced-and-checklist.md -->
|
|
896
|
+
|
|
897
|
+
# Python (FastMCP) — Advanced Features & Quality Checklist
|
|
898
|
+
|
|
899
|
+
Continues `11-python-implementation.md`. Advanced FastMCP capabilities, Python-specific best practices, and the finalization checklist.
|
|
900
|
+
|
|
901
|
+
## Advanced FastMCP Features
|
|
902
|
+
|
|
903
|
+
### Context Parameter Injection
|
|
904
|
+
|
|
905
|
+
FastMCP can automatically inject a `Context` parameter into tools for advanced capabilities like logging, progress reporting, resource reading, and user interaction:
|
|
906
|
+
|
|
907
|
+
```python
|
|
908
|
+
from mcp.server.fastmcp import FastMCP, Context
|
|
909
|
+
|
|
910
|
+
mcp = FastMCP("example_mcp")
|
|
911
|
+
|
|
912
|
+
@mcp.tool()
|
|
913
|
+
async def advanced_search(query: str, ctx: Context) -> str:
|
|
914
|
+
'''Advanced tool with context access for logging and progress.'''
|
|
915
|
+
|
|
916
|
+
# Report progress for long operations
|
|
917
|
+
await ctx.report_progress(0.25, "Starting search...")
|
|
918
|
+
|
|
919
|
+
# Log information for debugging
|
|
920
|
+
await ctx.log_info("Processing query", {"query": query, "timestamp": datetime.now()})
|
|
921
|
+
|
|
922
|
+
# Perform search
|
|
923
|
+
results = await search_api(query)
|
|
924
|
+
await ctx.report_progress(0.75, "Formatting results...")
|
|
925
|
+
|
|
926
|
+
# Access server configuration
|
|
927
|
+
server_name = ctx.fastmcp.name
|
|
928
|
+
|
|
929
|
+
return format_results(results)
|
|
930
|
+
|
|
931
|
+
@mcp.tool()
|
|
932
|
+
async def interactive_tool(resource_id: str, ctx: Context) -> str:
|
|
933
|
+
'''Tool that can request additional input from users.'''
|
|
934
|
+
|
|
935
|
+
# Request sensitive information when needed
|
|
936
|
+
api_key = await ctx.elicit(
|
|
937
|
+
prompt="Please provide your API key:",
|
|
938
|
+
input_type="password"
|
|
939
|
+
)
|
|
940
|
+
|
|
941
|
+
# Use the provided key
|
|
942
|
+
return await api_call(resource_id, api_key)
|
|
943
|
+
```
|
|
944
|
+
|
|
945
|
+
**Context capabilities:**
|
|
946
|
+
- `ctx.report_progress(progress, message)` — Report progress for long operations
|
|
947
|
+
- `ctx.log_info(message, data)` / `ctx.log_error()` / `ctx.log_debug()` — Logging
|
|
948
|
+
- `ctx.elicit(prompt, input_type)` — Request input from users
|
|
949
|
+
- `ctx.fastmcp.name` — Access server configuration
|
|
950
|
+
- `ctx.read_resource(uri)` — Read MCP resources
|
|
951
|
+
|
|
952
|
+
### Resource Registration
|
|
953
|
+
|
|
954
|
+
Expose data as resources for efficient, template-based access:
|
|
955
|
+
|
|
956
|
+
```python
|
|
957
|
+
@mcp.resource("file://documents/{name}")
|
|
958
|
+
async def get_document(name: str) -> str:
|
|
959
|
+
'''Expose documents as MCP resources.
|
|
960
|
+
|
|
961
|
+
Resources are useful for static or semi-static data that doesn't
|
|
962
|
+
require complex parameters. They use URI templates for flexible access.
|
|
963
|
+
'''
|
|
964
|
+
document_path = f"./docs/{name}"
|
|
965
|
+
with open(document_path, "r") as f:
|
|
966
|
+
return f.read()
|
|
967
|
+
|
|
968
|
+
@mcp.resource("config://settings/{key}")
|
|
969
|
+
async def get_setting(key: str, ctx: Context) -> str:
|
|
970
|
+
'''Expose configuration as resources with context.'''
|
|
971
|
+
settings = await load_settings()
|
|
972
|
+
return json.dumps(settings.get(key, {}))
|
|
973
|
+
```
|
|
974
|
+
|
|
975
|
+
**When to use Resources vs Tools:**
|
|
976
|
+
- **Resources:** for data access with simple parameters (URI templates)
|
|
977
|
+
- **Tools:** for complex operations with validation and business logic
|
|
978
|
+
|
|
979
|
+
### Structured Output Types
|
|
980
|
+
|
|
981
|
+
FastMCP supports multiple return types beyond strings:
|
|
982
|
+
|
|
983
|
+
```python
|
|
984
|
+
from typing import TypedDict
|
|
985
|
+
from dataclasses import dataclass
|
|
986
|
+
from pydantic import BaseModel
|
|
987
|
+
|
|
988
|
+
# TypedDict for structured returns
|
|
989
|
+
class UserData(TypedDict):
|
|
990
|
+
id: str
|
|
991
|
+
name: str
|
|
992
|
+
email: str
|
|
993
|
+
|
|
994
|
+
@mcp.tool()
|
|
995
|
+
async def get_user_typed(user_id: str) -> UserData:
|
|
996
|
+
'''Returns structured data - FastMCP handles serialization.'''
|
|
997
|
+
return {"id": user_id, "name": "John Doe", "email": "john@example.com"}
|
|
998
|
+
|
|
999
|
+
# Pydantic models for complex validation
|
|
1000
|
+
class DetailedUser(BaseModel):
|
|
1001
|
+
id: str
|
|
1002
|
+
name: str
|
|
1003
|
+
email: str
|
|
1004
|
+
created_at: datetime
|
|
1005
|
+
metadata: Dict[str, Any]
|
|
1006
|
+
|
|
1007
|
+
@mcp.tool()
|
|
1008
|
+
async def get_user_detailed(user_id: str) -> DetailedUser:
|
|
1009
|
+
'''Returns Pydantic model - automatically generates schema.'''
|
|
1010
|
+
user = await fetch_user(user_id)
|
|
1011
|
+
return DetailedUser(**user)
|
|
1012
|
+
```
|
|
1013
|
+
|
|
1014
|
+
### Lifespan Management
|
|
1015
|
+
|
|
1016
|
+
Initialize resources that persist across requests:
|
|
1017
|
+
|
|
1018
|
+
```python
|
|
1019
|
+
from contextlib import asynccontextmanager
|
|
1020
|
+
|
|
1021
|
+
@asynccontextmanager
|
|
1022
|
+
async def app_lifespan():
|
|
1023
|
+
'''Manage resources that live for the server's lifetime.'''
|
|
1024
|
+
# Initialize connections, load config, etc.
|
|
1025
|
+
db = await connect_to_database()
|
|
1026
|
+
config = load_configuration()
|
|
1027
|
+
|
|
1028
|
+
# Make available to all tools
|
|
1029
|
+
yield {"db": db, "config": config}
|
|
1030
|
+
|
|
1031
|
+
# Cleanup on shutdown
|
|
1032
|
+
await db.close()
|
|
1033
|
+
|
|
1034
|
+
mcp = FastMCP("example_mcp", lifespan=app_lifespan)
|
|
1035
|
+
|
|
1036
|
+
@mcp.tool()
|
|
1037
|
+
async def query_data(query: str, ctx: Context) -> str:
|
|
1038
|
+
'''Access lifespan resources through context.'''
|
|
1039
|
+
db = ctx.request_context.lifespan_state["db"]
|
|
1040
|
+
results = await db.query(query)
|
|
1041
|
+
return format_results(results)
|
|
1042
|
+
```
|
|
1043
|
+
|
|
1044
|
+
### Transport Options
|
|
1045
|
+
|
|
1046
|
+
FastMCP supports two main transport mechanisms:
|
|
1047
|
+
|
|
1048
|
+
```python
|
|
1049
|
+
# stdio transport (for local tools) - default
|
|
1050
|
+
if __name__ == "__main__":
|
|
1051
|
+
mcp.run()
|
|
1052
|
+
|
|
1053
|
+
# Streamable HTTP transport (for remote servers)
|
|
1054
|
+
if __name__ == "__main__":
|
|
1055
|
+
mcp.run(transport="streamable_http", port=8000)
|
|
1056
|
+
```
|
|
1057
|
+
|
|
1058
|
+
**Transport selection:**
|
|
1059
|
+
- **stdio:** command-line tools, local integrations, subprocess execution
|
|
1060
|
+
- **Streamable HTTP:** web services, remote access, multiple clients
|
|
1061
|
+
|
|
1062
|
+
## Code Best Practices
|
|
1063
|
+
|
|
1064
|
+
### Code Composability and Reusability
|
|
1065
|
+
|
|
1066
|
+
Prioritize composability and code reuse (the general rule is in `00-core.md`): extract common functionality into reusable helper functions, shared API clients, centralized error handling, composable business logic, and shared markdown/JSON field-selection & formatting. NEVER copy-paste similar code between tools; if you write similar logic twice, extract it. Share pagination, filtering, field selection, and formatting; centralize authentication/authorization.
|
|
1067
|
+
|
|
1068
|
+
### Python-Specific Best Practices
|
|
1069
|
+
|
|
1070
|
+
1. **Use Type Hints:** always include type annotations for function parameters and return values.
|
|
1071
|
+
2. **Pydantic Models:** define clear Pydantic models for all input validation.
|
|
1072
|
+
3. **Avoid Manual Validation:** let Pydantic handle input validation with constraints.
|
|
1073
|
+
4. **Proper Imports:** group imports (standard library, third-party, local).
|
|
1074
|
+
5. **Error Handling:** use specific exception types (`httpx.HTTPStatusError`, not generic `Exception`).
|
|
1075
|
+
6. **Async Context Managers:** use `async with` for resources that need cleanup.
|
|
1076
|
+
7. **Constants:** define module-level constants in UPPER_CASE.
|
|
1077
|
+
|
|
1078
|
+
## Quality Checklist
|
|
1079
|
+
|
|
1080
|
+
Before finalizing your Python MCP server implementation, ensure:
|
|
1081
|
+
|
|
1082
|
+
### Strategic Design
|
|
1083
|
+
- [ ] Tools enable complete workflows, not just API endpoint wrappers
|
|
1084
|
+
- [ ] Tool names reflect natural task subdivisions
|
|
1085
|
+
- [ ] Response formats optimize for agent context efficiency
|
|
1086
|
+
- [ ] Human-readable identifiers used where appropriate
|
|
1087
|
+
- [ ] Error messages guide agents toward correct usage
|
|
1088
|
+
|
|
1089
|
+
### Implementation Quality
|
|
1090
|
+
- [ ] FOCUSED IMPLEMENTATION: Most important and valuable tools implemented
|
|
1091
|
+
- [ ] All tools have descriptive names and documentation
|
|
1092
|
+
- [ ] Return types are consistent across similar operations
|
|
1093
|
+
- [ ] Error handling is implemented for all external calls
|
|
1094
|
+
- [ ] Server name follows format: `{service}_mcp`
|
|
1095
|
+
- [ ] All network operations use async/await
|
|
1096
|
+
- [ ] Common functionality is extracted into reusable functions
|
|
1097
|
+
- [ ] Error messages are clear, actionable, and educational
|
|
1098
|
+
- [ ] Outputs are properly validated and formatted
|
|
1099
|
+
|
|
1100
|
+
### Tool Configuration
|
|
1101
|
+
- [ ] All tools implement 'name' and 'annotations' in the decorator
|
|
1102
|
+
- [ ] Annotations correctly set (readOnlyHint, destructiveHint, idempotentHint, openWorldHint)
|
|
1103
|
+
- [ ] All tools use Pydantic BaseModel for input validation with Field() definitions
|
|
1104
|
+
- [ ] All Pydantic Fields have explicit types and descriptions with constraints
|
|
1105
|
+
- [ ] All tools have comprehensive docstrings with explicit input/output types
|
|
1106
|
+
- [ ] Docstrings include complete schema structure for dict/JSON returns
|
|
1107
|
+
- [ ] Pydantic models handle input validation (no manual validation needed)
|
|
1108
|
+
|
|
1109
|
+
### Advanced Features (where applicable)
|
|
1110
|
+
- [ ] Context injection used for logging, progress, or elicitation
|
|
1111
|
+
- [ ] Resources registered for appropriate data endpoints
|
|
1112
|
+
- [ ] Lifespan management implemented for persistent connections
|
|
1113
|
+
- [ ] Structured output types used (TypedDict, Pydantic models)
|
|
1114
|
+
- [ ] Appropriate transport configured (stdio or streamable HTTP)
|
|
1115
|
+
|
|
1116
|
+
### Code Quality
|
|
1117
|
+
- [ ] File includes proper imports including Pydantic imports
|
|
1118
|
+
- [ ] Pagination is properly implemented where applicable
|
|
1119
|
+
- [ ] Filtering options are provided for potentially large result sets
|
|
1120
|
+
- [ ] All async functions are properly defined with `async def`
|
|
1121
|
+
- [ ] HTTP client usage follows async patterns with proper context managers
|
|
1122
|
+
- [ ] Type hints are used throughout the code
|
|
1123
|
+
- [ ] Constants are defined at module level in UPPER_CASE
|
|
1124
|
+
|
|
1125
|
+
### Testing
|
|
1126
|
+
- [ ] Server runs successfully: `python your_server.py --help`
|
|
1127
|
+
- [ ] All imports resolve correctly
|
|
1128
|
+
- [ ] Sample tool calls work as expected
|
|
1129
|
+
- [ ] Error scenarios handled gracefully
|