上下文编织 是 AI Skill Hub 本期精选MCP工具之一。综合评分 7.5 分,整体质量较高。我们推荐使用将其纳入你的 AI 工具库,帮助提升工作效率。
上下文编织 是一款遵循 MCP(Model Context Protocol)标准协议的 AI 工具扩展。通过 MCP 协议,它可以让 Claude、Cursor 等主流 AI 客户端直接访问和操作外部工具、数据源和服务,实现 AI 能力的无缝扩展。无论是文件操作、数据库查询还是 API 调用,都可以通过自然语言在 AI 对话中直接触发,极大提升生产效率。
上下文编织 是一款遵循 MCP(Model Context Protocol)标准协议的 AI 工具扩展。通过 MCP 协议,它可以让 Claude、Cursor 等主流 AI 客户端直接访问和操作外部工具、数据源和服务,实现 AI 能力的无缝扩展。无论是文件操作、数据库查询还是 API 调用,都可以通过自然语言在 AI 对话中直接触发,极大提升生产效率。
# 方式一:通过 Claude Code CLI 一键安装
claude skill install https://github.com/dgenio/contextweaver
# 方式二:手动配置 claude_desktop_config.json
{
"mcpServers": {
"-----": {
"command": "npx",
"args": ["-y", "contextweaver"]
}
}
}
# 配置文件位置
# macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
# Windows: %APPDATA%/Claude/claude_desktop_config.json
# 安装后在 Claude 对话中直接使用 # 示例: 用户: 请帮我用 上下文编织 执行以下任务... Claude: [自动调用 上下文编织 MCP 工具处理请求] # 查看可用工具列表 # 在 Claude 中输入:"列出所有可用的 MCP 工具"
// claude_desktop_config.json 配置示例
{
"mcpServers": {
"_____": {
"command": "npx",
"args": ["-y", "contextweaver"],
"env": {
// "API_KEY": "your-api-key-here"
}
}
}
}
// 保存后重启 Claude Desktop 生效
The MCP context gateway for tool-heavy agents. Drop contextweaver in front of your MCP servers and the model sees a bounded ChoiceCard shortlist instead of every tool schema, plus an artifact-backed firewall that swaps a huge raw tool result for a compact summary. Deterministic, no model in the loop, and 42-84 % fewer prompt tokens on the committed benchmarks.
Who it's for: anyone whose agent — Claude Desktop, Cursor, VS Code, or a custom loop — keeps tripping over "too many tools" or "a 16 KB tool result blew up my prompt."
pip install contextweaver
contextweaver demo --scenario killer # 60-second taste — no API key, no network
Use it for real → the MCP gateway quickstart (Claude Desktop / Copilot / custom MCP clients), backed by the MCP Context Gateway architecture. Already have a loop and not sure which piece you need? The two engines also work routing-only or firewall-only.
<p align="center"> <img src="docs/assets/hero.svg" alt="contextweaver architecture: Context Engine plus Routing Engine, with the Context Firewall storing large tool outputs out of band and the Routing Engine narrowing a 100-tool catalog to 5 ChoiceCards."/> </p>
1150+ tests passing · minimal core dependencies · deterministic by default · Python 3.10–3.13
<p align="center"> <img src="docs/assets/context_rot.svg" width="660" alt="Context-rot curve: as the tool catalog grows from 83 to 1328 tools, a naive route prompt carries every schema (line climbs on a log scale) while contextweaver stays flat at 5 ChoiceCards; contextweaver's correct-tool recall@5 erodes from 36 percent to 10 percent as distractor tools accumulate."/> </p>
As an agent's tool catalog grows, a naive "show every schema" route prompt balloons while the right tool gets harder to find — context rot. contextweaver keeps the model-visible surface bounded (5ChoiceCards, not 1,328 schemas), so the route prompt stays flat and deterministic. Reproduce the curve with no API key:docs/context_rot.md.
<p align="center"> <img src="docs/assets/demo.svg" alt="Animated terminal recording of python -m contextweaver demo: load a 40-tool catalog, build a 9-node routing graph, narrow to 5 ChoiceCards for the query 'find unpaid invoices and send a reminder email', build a phase-answer context pack, and print the 321-character compiled prompt."/> </p>
<p align="center"> <img src="docs/assets/before_after.svg" alt="Before vs after token comparison from examples/before_after.py: 417 raw prompt tokens without contextweaver vs 126 final prompt tokens with contextweaver — a 70 percent reduction, 291 tokens saved, budget compliant."/> </p>
📖 Docs · 🎬 Showcase · 🧩 Where it fits · 🗺️ Ecosystem map · ❓ FAQ · 📊 Scorecard · 📈 Adopter benchmark report · 🧭 Which pattern fits? · 🛠 Cookbook · 🍳 Recipes · 📉 Context rot demo · 🎬 Replay demo (.cast)
---
pip install contextweaver
contextweaver ships with a minimal, opinionated core: tiktoken, PyYAML, rank-bm25, mcp, jsonschema, Typer, and Rich. These power token budgeting, YAML catalog/config files, the default lexical retrieval backend, the MCP proxy/gateway runtime, schema validation, and the CLI.
Optional capabilities are gated behind extras so the core install stays small:
| Extra | What it adds |
|---|---|
contextweaver[cli] | Deprecated no-op alias; Typer/Rich now ship in core |
contextweaver[weaver-spec] | Weaver Stack contract adapters (weaver_contracts) |
contextweaver[fastmcp] | FastMCP catalog adapter and discovery helpers |
contextweaver[crewai] | CrewAI runtime integration |
contextweaver[pydantic-ai] | Pydantic AI runtime integration |
contextweaver[smolagents] | Hugging Face smolagents runtime integration |
contextweaver[agno] | Agno runtime integration |
contextweaver[langchain] | LangChain integration helpers |
contextweaver[voice] | Pipecat voice-agent integration |
contextweaver[retrieval] | Fuzzy lexical matching backend (rapidfuzz) |
contextweaver[embeddings] | Sentence-transformers embedding backend |
contextweaver[sqlite] | SQLite store install contract (stdlib-backed today) |
contextweaver[mem0] | Mem0 external-memory backend |
contextweaver[otel] | OpenTelemetry tracing + metrics export |
contextweaver[e2e-eval] | Optional real-model benchmark hook (no dependency today) |
contextweaver[docs] | MkDocs documentation toolchain |
contextweaver[dev] | Test, lint, type-check, and fixture toolchain |
contextweaver[ann] | Approximate-nearest-neighbour backend (reserved) |
contextweaver[graph] | NetworkX-backed graph ops (reserved) |
contextweaver[all] | Convenience bundle for broad optional runtime capabilities |
Or from source:
git clone https://github.com/dgenio/contextweaver.git
cd contextweaver
pip install -e ".[dev]"
For a guided setup with prerequisites, three runnable examples, expected output, and next steps, see docs/quickstart.md.
Already have an agent and not sure which piece you need? See Which pattern fits my use case? — a symptom-based decision tree (long conversations → full pipeline; 50+ tools → routing-only; huge tool outputs → firewall-only) that points each branch to one concrete next step.
| Script | Description |
|---|---|
minimal_loop.py | Basic event ingestion → context build |
full_agent_loop.py | End-to-end route → call → interpret → answer runtime loop |
tool_wrapping.py | Context firewall in action |
routing_demo.py | Build catalog → route queries → choice cards |
before_after.py | Side-by-side token comparison: WITHOUT vs WITH contextweaver |
mcp_adapter_demo.py | MCP adapter: tool conversion, session loading, firewall |
a2a_adapter_demo.py | A2A adapter: agent cards, multi-agent sessions |
crewai_adapter_demo.py | CrewAI adapter: BaseTool → catalog → routing |
pydantic_ai_adapter_demo.py | Pydantic AI adapter: tools + lossless message round-trip |
smolagents_adapter_demo.py | smolagents adapter: tools + MultiStepAgent step-log ingestion |
agno_adapter_demo.py | Agno adapter: toolkit → catalog + session-history ingestion |
langchain_memory_demo.py | LangChain memory replacement: InMemoryChatMessageHistory vs contextweaver |
cookbook/byot_recipe.py | Bring-your-own-tools cookbook recipe — wrap plain Python callables and route |
cookbook/firewall_drilldown_recipe.py | Cookbook recipe: firewall a large tool result, then drill into the artifact |
architectures/catalog_showcase/ | **Start-here** reference architecture — 65-tool catalog → 5-card shortlist, single-tool schema hydration, firewall on a ~3 KB result, final BuildStats ([guide](docs/architectures/catalog_showcase.md)) |
architectures/langgraph_agent_loop/ | contextweaver **inside** a LangGraph StateGraph (route → execute → answer), firewall on a ~21 KB log dump, cross-turn retention; optional framework with a hand-rolled fallback ([guide](docs/architectures/langgraph_agent_loop.md)) |
architectures/eval_artifact_profile/ | Agent-safe context shaping for offline-evaluation reports — never surfaces V_hat without support diagnostics ([guide](docs/architectures/eval_artifact_profile.md)) |
architectures/mcp_context_gateway/ | Launch reference architecture — 60-tool MCP-style gateway end-to-end: ChoiceCards, lazy schema hydration, context firewall on a 16 KB result, artifact-backed answer prompt ([guide](docs/architectures/mcp_context_gateway.md)) |
architectures/mcp_context_gateway/main_real.py | Same flow, run against verbatim tools/list snapshots of MIT-licensed reference MCP servers (server-time, server-filesystem, server-everything) committed under real_catalogs/ |
recipes/serve_gateway.py | Minimal stdio launcher used by the [Claude Desktop](docs/recipes/claude_desktop.md) and [GitHub Copilot](docs/recipes/github_copilot.md) recipes |
architectures/slack_ops_bot/ | Production reference architecture — internal Slack ops bot with ~50 tools, firewall on log/grep outputs, persistent facts ([guide](docs/architectures/slack_ops_bot.md)) |
make example # run all examples
---
Looking for "where does contextweaver fit alongside my runtime?" — start with the How contextweaver Fits positioning page, then jump into the Cookbook for copy-paste recipes.
| Framework | Guide | Use Case |
|---|---|---|
| MCP | [Guide](docs/integration_mcp.md) | Tool conversion, session loading, firewall · [Security note](docs/integration_mcp.md#security-considerations) |
| A2A | [Guide](docs/integration_a2a.md) | Agent cards, multi-agent sessions |
| FastMCP | [Cookbook recipe](docs/cookbook.md#1-fastmcp--contextweaver-routing) | Composed MCP servers → bounded-choice routing |
| LlamaIndex | [Guide](docs/integration_llamaindex.md) | RAG + tools with budget control |
| OpenAI Agents SDK | [Guide](docs/integration_openai_adk.md) | Swarm hand-offs with unified context |
| Google ADK / Vertex AI | [Guide](docs/integration_google_adk.md) | Gemini tool-use with context budgets |
| LangChain + LangGraph | [Guide](docs/integration_langchain.md) | Chain + graph agents with firewall |
| Pipecat | [Guide](docs/integration_pipecat.md) | Real-time voice agents with async context build |
| CrewAI | [Guide](docs/integration_crewai.md) | Role-based crews with bounded tool shortlists |
| Pydantic AI | [Guide](docs/integration_pydantic_ai.md) | Type-safe agents with lossless message round-trip |
| smolagents | [Guide](docs/integration_smolagents.md) | Hugging Face CodeAgent / ToolCallingAgent with step-log ingestion |
| Agno | [Guide](docs/integration_agno.md) | Toolkit-routed agents; layers above Agno Memory |
---
Snapshot of the launch landscape as of 2026-05-31 — see footnotes for the versions referenced and the evidence behind each non-trivial claim. Will be refreshed each minor release.
| Approach | Tool routing | History compaction | Sensitivity firewall | Deterministic | MCP-native |
|---|---|---|---|---|---|
| **contextweaver** (this repo, [v0.13.4](https://pypi.org/project/contextweaver/0.13.4/)) | ✅ Bounded DAG + beam search · per-phase ChoiceCards [^cw-route] | ✅ Phase-aware budgeted compilation · 42-84 % token reduction vs naïve [^cw-bench] | ✅ Built-in (size-gated, with ArtifactRef drilldown) [^cw-fire] | ✅ By default — tie-break by sorted IDs [^cw-det] | ✅ Native proxy + gateway runtimes per docs/gateway_spec.md [^cw-mcp] |
| **Naïve concat-everything** | ❌ No router · prompt carries every tool schema | ❌ No compaction · prompt grows with turn count | ❌ Raw outputs in the prompt | ⚠️ Only if the upstream LLM is | ⚠️ Compatible but no shaping |
| **LangGraph memory** ([0.6.x](https://github.com/langchain-ai/langgraph/releases)) | ❌ Out of scope — LangGraph routes state, not tools | ⚠️ Optional via ConversationSummaryMemory (LLM-based, non-deterministic) [^lg-mem] | ❌ Not provided | ⚠️ Workflow yes; memory summarizer no | ⚠️ Possible via custom adapter, not first-class |
| **LlamaIndex retrievers** ([0.11.x](https://github.com/run-llama/llama_index/releases)) | ⚠️ Tool retrieval via ObjectIndex is unranked similarity, no bounded routing | ⚠️ ChatMemoryBuffer token-bounded · no phase awareness [^li-mem] | ❌ Not provided · large outputs flow through verbatim | ⚠️ Retriever yes; summarizer no | ⚠️ Possible via custom tool wrapper |
| **Raw MCP** ([modelcontextprotocol v0.1](https://modelcontextprotocol.io)) | ❌ Servers expose tools; routing across many servers is the client's problem | ❌ Out of scope for the protocol | ❌ Out of scope for the protocol | ✅ Wire protocol is deterministic | ✅ — _is_ the protocol |
[^cw-route]: contextweaver.routing.router.Router ships a four-stage pipeline (retrieve → rerank → navigate → pack) with deterministic tie-break by id. Locked by tests/test_cards.py::test_make_choice_cards_byte_identical_stable_order. [^cw-bench]: Range from the committed scorecard (benchmarks/scorecard.md) using tiktoken.cl100k_base against the naïve baseline (scripts/baseline_naive.py). Average 64.3 %; min 41.6 % on long_conversation.jsonl; max 84.3 % on tiny_payload.jsonl. [^cw-fire]: contextweaver.context.firewall.apply_firewall plus ArtifactRef drilldown selectors (head / lines / json_keys / rows). See docs/context_firewall.md and the firewall_drilldown_recipe. [^cw-det]: Determinism is an invariant — see docs/agent-context/invariants.md and make scorecard-check in the CI gate. [^cw-mcp]: src/contextweaver/adapters/mcp_proxy.py, mcp_gateway.py, mcp_proxy_server.py, mcp_gateway_server.py. Bound by docs/gateway_spec.md. [^lg-mem]: LangGraph 0.6 docs ("Memory"): ConversationSummaryMemory requires an LLM round-trip to produce a summary; output is non-deterministic across runs even with temperature=0 due to model jitter. [^li-mem]: LlamaIndex 0.11 docs ("Chat memory"): ChatMemoryBuffer(token_limit=...) truncates oldest-first; no phase awareness and no dependency closure.
Most agent frameworks offer one or two of these capabilities. contextweaver ships all five as a composable, framework-agnostic layer that runs under whichever framework you already have.
---
Q: What token budgets should I use? Start with the defaults (route=2000, call=3000, interpret=4000, answer=6000). Inspect pack.stats after each build and increase any phase that drops too many items.
Q: My tool result was summarized. Why? The context firewall intercepts every tool_result item (not just large ones). Raw data is stored out-of-band; access it via mgr.artifact_store.get("artifact:<item_id>"). Provide a custom Summarizer to control how the summary is generated.
Q: How do I debug what was kept or dropped? Inspect pack.stats (a BuildStats object) after every build_sync() / build() call: included_count, dropped_count, dropped_reasons, dedup_removed.
Q: Does this work with [framework X]? Yes, contextweaver is framework-agnostic — it compiles context; you send pack.prompt to any LLM or framework. See dedicated guides for MCP, A2A, LlamaIndex, LangChain + LangGraph, OpenAI Agents SDK, Google ADK / Vertex AI, Pipecat, CrewAI, Pydantic AI, smolagents, and Agno. If your runtime isn't listed, the bring-your-own-tools cookbook recipe is the canonical starting point.
Q: What's the performance overhead? Typically 10–50 ms for a context build (depends on event log size and deduplication). For real-time / async agents, run build_sync() in a worker thread (e.g. await asyncio.to_thread(mgr.build_sync, phase, query)) so the synchronous pipeline does not block the event loop. If an offline or air-gapped run prints a tiktoken cl100k_base encoding unavailable warning, see the troubleshooting note; the fallback keeps budget enforcement deterministic.
See docs/troubleshooting.md for the full troubleshooting guide, debugging techniques, optimisation tips, and 10+ common issues with solutions.
---
高质量的开源MCP工具,值得关注
AI Skill Hub 为第三方内容聚合平台,本页面信息基于公开数据整理,不对工具功能和质量作任何法律背书。
建议在沙箱或测试环境中充分验证后,再部署至生产环境,并做好必要的安全评估。
✅ Apache 2.0 — 宽松开源协议,可商用,需保留版权声明和 NOTICE 文件,含专利授权条款。
经综合评估,上下文编织 在MCP工具赛道中表现稳健,质量良好。如果你已有明确的使用需求,可以直接上手体验;如果还在评估阶段,建议对比同类工具后再做决策。
| 原始名称 | contextweaver |
| 原始描述 | 开源MCP工具:Budget-aware context compilation and context firewall for tool-heavy AI agents.。⭐6 · Python |
| Topics | ai-agentscontext-managementprompt-engineering |
| GitHub | https://github.com/dgenio/contextweaver |
| License | Apache-2.0 |
| 语言 | Python |
收录时间:2026-06-02 · 更新时间:2026-06-02 · License:Apache-2.0 · AI Skill Hub 不对第三方内容的准确性作法律背书。
选择 Agent 类型,复制安装指令后粘贴到对应客户端