使用说明
主控程序
三个基元。无限的能力。
构建可以搜索、获取和执行的AI代理——具有任何后端、任何规模、完全安全。
import { createMCPServer } from 'mcp'
const server = createMCPServer({
search: webSearch(),
fetch: httpFetch(),
do: evaluate()
})
问题
人工智能代理被困在一个支离破碎的世界里。
每个功能都需要一个单独的工具。每个工具都需要往返模型。每次往返都要花费代币、时间和可靠性。
需要搜索网络、获取文档、提取数据和保存结果的代理可能会 5-10次连续的工具调用 --每个都要求模型:
- 接收之前的结果
- 决定下一步做什么
- 格式化新的工具调用
- 等待执行
- 重复
这种模式有三个致命的缺陷:
代币爆炸。 上下文窗口填充中间结果。一个应该花费2000个代币的工作流程会膨胀到150000个。
延迟倍增。 每个工具调用都需要一个完整的模型推理。十个工具意味着十次推理往返。
脆弱的编排。 模型必须正确排序每一步。一个错误的决定就会导致失败。
有更好的办法。
洞察力
LLM是更好的程序员,而不是工具调用者。
他们已经接受了数十亿行代码的训练。他们了解TypeScript接口、异步/等待模式、错误处理、循环和条件。
但是结构化工具调用语法呢?这是人为的。这从未出现在他们的训练数据中。每一次工具调用都是与自身优势相反的模型。
解决方案:让模型编写代码。
给模型一个接受代码的工具,而不是N个连续的工具调用。该代码可以在一次执行中调用函数、处理错误、循环结果和组合操作。
// Before: 5 tool calls, 5 round-trips, 150K tokens
tool_call: search({ query: "latest AI research" })
tool_call: fetch({ url: results[0].url })
tool_call: extract({ content: page, fields: ["title", "abstract"] })
tool_call: search({ query: extracted.abstract })
tool_call: save({ data: relatedPapers })
// After: 1 tool call, 1 round-trip, 2K tokens
tool_call: do({
code: `
const results = await search("latest AI research")
const page = await fetch(results[0].url)
const { title, abstract } = extractFields(page, ["title", "abstract"])
const related = await search(abstract)
return { title, abstract, related }
`
})
同样的能力。 代币减少98%。 一个推论,而不是五个。
三个原始人
每个AI代理的功能都可以简化为三个操作:
search --查找信息
查询语料库。发现资源。匹配图案。
search("users who signed up last week")
search("*.config.json")
search("SELECT * FROM orders WHERE status = 'pending'")
fetch --检索资源
通过标识符获取特定对象。
fetch("https://api.example.com/users/123")
fetch("/etc/nginx/nginx.conf")
fetch("order:ord_abc123")
do --执行操作
运行具有搜索和获取权限(以及您提供的任何其他绑定)的代码。
do(`
const users = await search("premium users")
const enriched = await Promise.all(
users.map(async u => ({
...u,
profile: await fetch(u.profileUrl)
}))
)
return enriched.filter(u => u.profile.verified)
`)
这 do 原始是魔法发生的地方。这不仅仅是代码执行—— 可组合编排.
设计安全
任意执行代码听起来很危险。如果设计得当,它就不会。
执行环境是一个V8隔离 零环境能力:
- 没有文件系统访问权限
- 无网络访问
- 无环境变量
- 无系统调用
代码与外界交互的唯一方式是通过 显式提供的绑定.
do({
code: `
// These work because they're provided bindings
const results = await search("query")
const doc = await fetch("doc:123")
// These fail because they're not provided
await fetch("https://evil.com") // Error: not a valid resource
require('fs').readFileSync('/etc/passwd') // Error: require is not defined
process.env.API_KEY // Error: process is not defined
`,
bindings: {
search: scopedSearch, // Your implementation
fetch: scopedFetch // Your implementation
}
})
这是 基于能力的安全.Code只能执行您明确允许的操作。凭据永远不会进入沙盒。攻击面正是您定义的面。
可配置范围
这种模式的力量来自可配置范围。相同的三个原语适用于任何域:
Web研究代理
createMCPServer({
search: braveSearch({ apiKey }),
fetch: httpFetch({ allowedDomains: ['*.gov', '*.edu'] }),
do: {
bindings: { search, fetch },
types: WEB_TYPES
}
})
数据库代理
createMCPServer({
search: db.query,
fetch: db.get,
do: {
bindings: {
search: db.query,
fetch: db.get,
db: { create: db.create, update: db.update, delete: db.delete }
},
types: generateTypes(db.schema)
}
})
文件系统代理
createMCPServer({
search: fs.glob,
fetch: fs.read,
do: {
bindings: {
search: fs.glob,
fetch: fs.read,
fs: { write: fs.write, mkdir: fs.mkdir, move: fs.move }
},
types: FS_TYPES
}
})
Git代理
createMCPServer({
search: git.log,
fetch: git.show,
do: {
bindings: {
search: git.log,
fetch: git.show,
git: { commit: git.commit, branch: git.branch, merge: git.merge }
},
types: GIT_TYPES
}
})
图书馆不知道沙盒。它们导出类型化函数。此服务器将它们连接到安全的执行上下文中。
运作原理
1.定义您的范围
const scope = {
bindings: {
search: mySearchImpl,
fetch: myFetchImpl,
custom: myCustomApi
},
types: `
declare function search(query: string): Promise<Result[]>
declare function fetch(id: string): Promise<Document>
declare const custom: {
process(data: unknown): Promise<ProcessedData>
}
`
}
2.创建服务器
const server = createMCPServer({
search: scope.bindings.search,
fetch: scope.bindings.fetch,
do: scope
})
3.联系克劳德
{
"mcpServers": {
"my-agent": {
"command": "npx",
"args": ["my-mcp-server"]
}
}
}
4.让Claude编写代码
当Claude需要完成一项复杂的任务时,它会根据你的类型定义编写TypeScript。代码在沙盒V8隔离中执行,只有您的绑定可用。
克劳德看到:
// Available APIs (from your types)
declare function search(query: string): Promise<Result[]>
declare function fetch(id: string): Promise<Document>
declare const custom: { process(data: unknown): Promise<ProcessedData> }
克劳德写道:
const results = await search("important documents")
const docs = await Promise.all(results.map(r => fetch(r.id)))
const processed = await custom.process(docs)
return processed
你得到:可组合、高效、安全的人工智能操作。
模板
常见用例的预构建配置:
import { templates } from 'mcp'
// Knowledge graph / memory
const memory = templates.memory({ storage: memoryStore })
// Filesystem operations
const filesystem = templates.filesystem({ root: '/data', readonly: false })
// SQL database
const database = templates.database({ connection: pgClient })
// Git repository
const git = templates.git({ repo: repoPath })
// Web research
const web = templates.web({ searchProvider: 'brave', apiKey })
// Shell commands (with safety analysis)
const shell = templates.shell({ allowedCommands: ['ls', 'cat', 'grep'] })
每个模板都是一个 DoScope 将三个原语连接到特定后端的配置。
为什么这很重要
面向AI代理开发人员
停止为N个功能构建N个工具。构建三个图元。配置作用域。让模型组成。
面向后端库作者
停止构建沙盒。导出类型化函数。让这个库处理执行安全。
对于组织
利用基于功能的安全性,获得任意代码执行的能力。通过审核绑定来审核可能的情况。
愿景
每个后端都变成了一个有三条线路的MCP服务器:
createMCPServer({ search, fetch, do: { bindings, types } })
每个AI代理都有相同的三个工具:
search--查找信息fetch--检索资源do--组合操作
区别在于范围。数据库代理 search 查询表。文件系统代理 search 地球轨道。网络代理 search 呼唤勇敢。
但这种模式是普遍的。当模式具有普遍性时,代理变得可组合。
一个知道的代理人 search/fetch/do 可以与任何后端一起工作。交换作用域,保留代理。
这是人工智能能力的未来: 三个原语,无限范围,完全安全.
入门指南
npm install mcp
import { createMCPServer, templates } from 'mcp'
// Quick start with a template
const server = createMCPServer(templates.web({
searchProvider: 'brave',
apiKey: process.env.BRAVE_API_KEY
}))
// Or build your own scope
const server = createMCPServer({
search: mySearch,
fetch: myFetch,
do: {
bindings: { search: mySearch, fetch: myFetch, custom: myApi },
types: MY_TYPES
}
})
// Start the server
server.listen()
路线图
该项目遵循TDD(红色→ 绿色→ 重构)方法。跟踪进度 bd list.
史诗
| ID | 史诗 | 任务 |
|---|---|---|
mcp-jxp |
设置:项目脚手架 | Package.json、tsconfig、目录结构 |
mcp-h3t |
核心:服务器工厂和类型 | MCPServerConfig,创建MCPServer(),类型导出 |
mcp-7oh |
传输:标准和HTTP/SSE | Stdio传输、HTTP处理程序、SSE流媒体 |
mcp-xss |
Auth:多模式身份验证 | 匿名,OAuth 2.1,API密钥,中间件 |
mcp-ogn |
工具:搜索、提取、执行 | 使用ai评估沙盒的三个原语 |
mcp-xey |
范围:绑定和类型 | DoScope接口、类型生成、验证 |
mcp-txs |
模板:预构建配置 | Web、数据库、文件系统、git、内存 |
mcp-c1n |
工作者:Cloudflare部署 | Worker入口、wrangler配置、速率限制、CLI |
TDD工作流程
每个任务都跟随Red→ 绿色→ 重构:
# Find next task
bd ready
# Start work (write failing test)
bd update mcp-jxp.1 --status in_progress
# Implement (make test pass)
bd update mcp-jxp.2 --status in_progress
# Refactor and complete
bd close mcp-jxp.1
bd close mcp-jxp.2
许可证
麻省理工学院
