mcp-context-engineering
mcp-context-engineering
一个小巧、可运行的项目,演示 MCP 服务器的上下文工程:让 Model Context Protocol 服务器在模型上下文窗口中占用的空间保持很小,从而使代理更便宜、更准确。
问题
当 MCP 客户端(Claude Desktop、Cursor、SDK 应用)连接到 MCP 服务器时,它会把 每一个 对外发布的工具定义——名称、描述和完整的输入 schema——拉入模型的上下文。一个拥有 30-60+ 个工具的服务器,在代理做任何事之前,就可能在这些定义上消耗超过 10k 个 token。这会导致两个问题:
浪费 token。 你为代理永远不会调用的工具定义付费。
降低准确性。 模型会被无关工具分散注意力,更可能选错工具或凭空捏造参数。
Related MCP server: mcp-schema-bloat-fixer
两种技术
这个项目在一个包含 33 个模拟 "web-data" 工具的目录上实现了修复方案的两半部分(这些工具包括 Amazon、LinkedIn、TikTok、GitHub、Zillow、浏览器自动化、批量抓取等),并按逻辑分组组织。
限定你对外发布的工具范围。 只加载代理所需的能力——要么按整个 组(
GROUPS=social),要么 手动挑选 单个工具(TOOLS=web_data_amazon_product,...)。只有这些定义会进入上下文。优化这些工具返回的输出。 在抓取页面进入上下文之前,去除浪费 token 的 Markdown(粗体/斜体、图片语法、标题标记、代码围栏、链接 URL),保留模型实际会读到的每一个词。
实测影响(来自随附的离线报告)
完整目录 = 33 个工具 ≈ 4,556 个 token 的定义(如果未做范围限定就加载)。
配置 | 工具 | 定义 token 数 | 相比全部节省 |
默认(仅基础工具) | 3 | 506 | 89% |
| 9 | 1,318 | 71% |
| 11 | 1,566 | 66% |
| 14 | 1,973 | 57% |
| 3 | 416 | 91% |
| 6 | 917 | 80% |
| 33 | 4,556 | 0% |
对抓取页面执行 strip-markdown:243 → 149 个 token(减少约 39%)。
这些数字使用内置的启发式 token 估算器;如果安装了 tiktoken,可向报告传入 --tiktoken 以获得精确计数。关键在于 比例,它们是稳定的。
一句话总结这个模式
限定你加载的工具,精简它们返回的输出,让 MCP 服务器处理困难的部分。
代码地图
mcp-context-engineering/
├── src/mcp_context_engineering/
│ ├── __init__.py # Public API re-exports + version.
│ ├── tool_groups.py # Source of truth for groups: BASE_TOOLS + 8 logical
│ │ # groups (ecommerce, social, business, research,
│ │ # finance, app_stores, browser, advanced_scraping)
│ │ # and helpers (all_tool_names, total_tool_count).
│ ├── tool_catalog.py # Full catalog of 33 ToolSpecs: name, description,
│ │ # JSON input schema, and an OFFLINE mock handler
│ │ # each. Also MARKDOWN_TOOLS (which outputs to strip)
│ │ # and a SAMPLE_MARKDOWN_PAGE for the demo.
│ ├── context_config.py # The scoping brain. Reads PRO_MODE / GROUPS / TOOLS,
│ │ # resolves the exact tool set (resolve_context),
│ │ # and defines named PRESETS.
│ ├── strip_markdown.py # Dependency-free output optimiser: strips Markdown
│ │ # formatting, keeps words + code, links optional.
│ ├── token_utils.py # Lightweight offline token estimator + tool-def
│ │ # token counting (tiktoken optional).
│ └── server.py # The MCP server (official SDK low-level Server,
│ │ # stdio). Advertises only scoped tools; strips
│ │ # Markdown output. build_server() for tests.
├── scripts/
│ ├── run_server.py # Launch the server over stdio (what a client runs).
│ └── token_report.py # Offline demo: prints the savings tables above.
├── examples/
│ ├── claude_desktop_social_agent.json # config: one group
│ ├── claude_desktop_price_monitor.json # config: hand-picked tools
│ └── claude_desktop_pro_mode.json # config: everything (baseline)
├── tests/
│ └── test_context_engineering.py # 23 offline tests (unittest)
├── requirements.txt # Just the official `mcp` SDK (tiktoken optional).
├── .env.example # All config vars, documented.
└── .gitignore各部分如何配合
tool_groups.py 定义哪些工具 名称 属于哪个组。tool_catalog.py 为每个名称提供完整的定义(描述 + schema)和一个模拟处理器。context_config.py 读取环境变量并决定要暴露的确切名称子集。server.py 向 context_config 请求该子集,仅通过 tools/list 发布这些定义,并且——当 MARKDOWN_TOOLS 工具被调用时——在返回结果之前,将其输出经过 strip_markdown.py 处理。token_utils.py 为离线的 token_report.py 提供支持,后者在不接触网络的情况下量化这两项收益。
数据流
flowchart TD
subgraph Config["Configuration (env vars)"]
E["PRO_MODE / GROUPS / TOOLS<br/>STRIP_MARKDOWN"]
end
E --> RC["context_config.resolve_context()"]
TG["tool_groups.py<br/>(group -> tool names)"] --> RC
RC -->|"scoped list of tool names"| SRV["server.py (MCP Server)"]
TC["tool_catalog.py<br/>(name -> description, schema, handler)"] --> SRV
subgraph MCP["MCP session (stdio)"]
CLIENT["MCP client / LLM agent"]
SRV
end
SRV -->|"tools/list: ONLY scoped definitions"| CLIENT
CLIENT -->|"tools/call(name, args)"| SRV
SRV -->|"handler() output"| STRIP["strip_markdown.py<br/>(markdown tools only)"]
STRIP -->|"trimmed text"| CLIENT
RC -.offline.-> REPORT["scripts/token_report.py"]
TC -.offline.-> REPORT
TU["token_utils.py"] -.-> REPORT
REPORT -.-> OUT["savings tables"]快速开始
# 1. (optional) create a virtualenv
python -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
# 2. install the one dependency
pip install -r requirements.txt
# 3. see the token savings - fully offline, no key, no network
python scripts/token_report.py
python scripts/token_report.py --json # machine-readable
# 4. run the tests
python -m unittest discover -s tests -v运行 MCP 服务器
该服务器通过 stdio 使用 MCP 协议通信,并且完全通过环境变量进行配置:
# default: just the small base tool set
python scripts/run_server.py
# a focused social-media agent
GROUPS=social python scripts/run_server.py
# hand-pick exactly the tools a price monitor needs
TOOLS=web_data_amazon_product,web_data_ebay_product,web_data_google_shopping \
python scripts/run_server.py
# the un-scoped baseline (loads everything)
PRO_MODE=true python scripts/run_server.py
# disable output trimming
STRIP_MARKDOWN=false GROUPS=social python scripts/run_server.py有效的组 ID:ecommerce、social、business、research、finance、app_stores、browser、advanced_scraping。有关变量的完整列表,请参阅 .env.example。
接入 MCP 客户端
将 examples/ 中的某个文件复制到你的客户端服务器配置中(对于 Claude Desktop,即 claude_desktop_config.json),将 /ABSOLUTE/PATH 替换为你代码检出目录的路径,然后重启客户端。这三个示例分别展示了限定的组、手动挑选的集合,以及加载全部内容的基线配置。
关于工具的说明
本项目中的每个工具处理器都返回 预设的离线示例数据。任何地方都没有 API 密钥,也没有网络访问——目标是演示上下文工程模式,而不是抓取真实网站。要让它变成真实实现,请将 tool_catalog.py 中的处理器替换为对实际 web-data 后端的调用,并从环境变量中读取其凭据(占位符 WEB_DATA_API_KEY 已在 .env.example 中说明)。
基于 / 灵感来源
Model Context Protocol Python SDK —— 该服务器使用的官方 SDK:https://github.com/modelcontextprotocol/python-sdk
协议文档与规范: https://modelcontextprotocol.io
Bright Data MCP server —— 一个开源 MCP 服务器,推广了此处所模拟的工具组限定和 strip-markdown 输出优化:https://github.com/brightdata/brightdata-mcp
许可证
MIT(如果存在 LICENSE 文件请参阅,否则请将示例代码视为 MIT 许可)。
This server cannot be deployed
Maintenance
Related MCP Connectors
- WauldoOAuthcom.wauldo
Stateless agentic tools over MCP: concept extraction, long-context, knowledge graph, planning.
Find, vet, and run MCP tools through a secure audited gateway with prompt-injection risk scoring
MCP server for your apps' tools and custom tools, plus hosted AI agents and approval-gated workflows
Security & DLP proxy for MCP: tool-poisoning scans, PII redaction on tool args/results. Beta.
Related MCP Servers
- AlicenseNot gradedqualityCmaintenanceReduces AI token consumption by optimizing MCP tool definitions and responses, with a probe for measurement and a gate for filtered tool exposure and cost reduction.MIT
- AlicenseNot gradedqualityBmaintenanceReduces token costs from MCP tool schemas by analyzing bloat, compressing descriptions, and selecting only relevant tools for AI agents.MIT
- AlicenseNot gradedqualityDmaintenanceEnables analyzing and optimizing context window token usage by measuring, compressing, and eliminating waste from MCP tool definitions.44 npmMIT
- AlicenseNot gradedqualityAmaintenanceEnables AI agents to cut token usage by locally pruning, encoding, and summarizing MCP tool responses, with lossless recovery of original data when needed.32 npmApache 2.0