@goke/ mcp (英语)
任何转动 MCP 磁共振 服务器输入 CLI 。 连接到服务器,发现工具,用打出参数生成CLI命令——自动.
安装
npm install @goke/mcp goke
goke 是同级依赖(命令注册的CLI框架).
如何运作
MCP server Your CLI
┌──────────────────┐ ┌──────────────────────────┐
│ tools/list │──discover──▸ │ mycli notion-search │
│ - notion-search │ │ mycli notion-get-page │
│ - notion-get-… │ │ mycli notion-create-… │
│ (JSON Schema) │──coerce───▸ │ --query <string> │
│ │ │ --pageId <string> │
└──────────────────┘ └──────────────────────────┘
- 发现 - 电话
tools/list在 MCP 服务器上获取每个工具 + 其 JSON Schema - 登记册 ——每个工具创建 CLI 命令
--options来源于计划 - 缓存 ——工具计划缓存1小时(后续运行中无网络). 当无法进行活取时仍然使用已过期缓存( 无令牌, 401 on)
--help(中文(简体) ) - 执行 ——在引用时,连接到服务器,用被胁迫的参数调用工具
- 奥奥特 ——如果服务器返回401,则自动打开OAuth的浏览器,然后重试.
--help, (中文(简体) ),--version, (中文(简体) ),completions,没有args永远不会开始 OAuth
快开始
import { goke } from 'goke'
import { addMcpCommands } from '@goke/mcp'
import type { McpOAuthState, CachedMcpTools } from '@goke/mcp'
const cli = goke('notion-mcp-cli')
await addMcpCommands({
cli,
getMcpUrl: () => 'https://mcp.notion.com/mcp',
oauth: {
clientName: 'Notion CLI',
load: () => loadConfig().oauthState,
save: (state) => saveConfig({ oauthState: state }),
},
loadCache: () => loadConfig().cache,
saveCache: (cache) => saveConfig({ cache }),
})
cli.help()
cli.completions()
cli.parse()
如果 MCP 服务器是 HTTP, 请通过 getMcpUrl 即使用户没有符号. --help 和没有args必须运行 这样CLI可以显示 config / 登录指令. 使用 getMcpTransport 需要自定义或自定义运输时.
HTTP 接头符,通过 getHeaders数字 :
await addMcpCommands({
cli,
getMcpUrl: () => 'https://api.example.com/mcp',
getHeaders: () => {
const token = process.env.EXAMPLE_TOKEN || loadConfig().token
if (!token) return
return { Authorization: `Bearer ${token}` }
},
loadCache: () => loadConfig().cache,
saveCache: (cache) => saveConfig({ cache }),
})
就是这样。 MCP服务器曝光的每个工具都成为CLI命令:
notion-mcp-cli notion-search --query "meeting notes"
notion-mcp-cli notion-retrieve-page --page_id "abc123"
notion-mcp-cli notion-list-users
将 CLI 显示为 MCP 服务器
createMcpAction() 把你的整个CLI变成一个有一行的stdio MCP服务器. 每个 CLI 命令自动成为 MCP 工具. 您所附加的命令不在工具列表中 .
import { goke } from "goke"
import { z } from "zod"
import { createMcpAction } from "@goke/mcp"
const cli = goke("my-cli")
cli
.command("search", "Search pages")
.option("--query <query>", z.string().describe("Search query"))
.required()
.option("--limit [limit]", z.number().default(10).describe("Max results"))
.action((options) => {
return { results: findPages(options.query, options.limit) }
})
cli
.command("deploy <env>", "Deploy to environment")
.option("--dry-run", z.boolean().default(false).describe("Simulate"))
.action((env, options) => {
return options.dryRun ? `would deploy to ${env}` : deploy(env)
})
// Add MCP support — runs a stdio MCP server when the user invokes `my-cli mcp`
cli.command("mcp", "Start MCP server over stdio")
.action(createMcpAction({ cli }))
cli.help()
cli.completions()
cli.parse()
现在用户可以直接使用您的 CLI 或者说 以 MCP 服务器连接 :
# Use as a normal CLI
my-cli search --query "meeting notes"
my-cli deploy staging --dry-run
# Use as an MCP server (e.g. from Claude Desktop, Cursor, etc.)
my-cli mcp
以 MCP 运行时, 服务器会曝光 search 财务报告和审定财务报表 deploy 作为工具。 这个 mcp 命令本身被排除。 使用 Zod schema( 或任何标准 Schema) 选项键入 inputSchema mCP 工具定义中的属性.
inputSchema.required 这不是CLI <value> 语法. --query <query> 表示旗帜存在时需要一个值. 旗帜本身仍然是可选的,除非你连锁 .required()需要时 职位 喜欢 <env> 总是进去 required。 。 。 . .required() 升起旗帜 required 我也一样.
在客户端安装 MCP 服务器
用户可以在任何使用客户端的 MCP 服务器中安装您的 CLI @playwriter/install-mcp – 一个跨平台工具,用于处理每个主要MCP客户端的配置文件位置:
# Install in Claude Desktop
npx @playwriter/install-mcp my-cli --client claude-desktop
# Install in Cursor
npx @playwriter/install-mcp my-cli --client cursor
# Install in VS Code
npx @playwriter/install-mcp my-cli --client vscode
与任何客户端合作: claude-desktop, (中文(简体) ), cursor, (中文(简体) ), vscode, (中文(简体) ), windsurf, (中文(简体) ), claude-code, (中文(简体) ), opencode, (中文(简体) ), zed, (中文(简体) ), goose, (中文(简体) ), cline, (中文(简体) ), codex, (中文(简体) ), gemini-cli,以及 更多如果命令需要自定义参数,请通过完整命令字符串:
npx @playwriter/install-mcp 'npx my-cli mcp' --client cursor
createMcpAction 接受与 addCliToolsToMcp数字 :
| 选项 | 类型 | 默认 | 说明 |
|---|---|---|---|
cli | Goke | 所需经费 | 揭露CLI的例子 |
commandFilter | (name) => boolean | —— 说 | 附加过滤器( MCP 命令总是被排除) |
sanitizeToolName | (name) => string | —— 说 | 自定义工具名 |
serverName | string | CLI 名称 | MCP 服务器名称 |
serverVersion | string | '1.0.0' | MCP 服务器版本 |
createTransport | () => Transport | 静态 | 海关运输厂 |
高级 : addCliToolsToMcp
更多控制(使用自定义服务器,使用现有的MCP工具),使用 addCliToolsToMcp() 直接 :
import { Server } from "@modelcontextprotocol/sdk/server/index.js"
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
import { addCliToolsToMcp } from "@goke/mcp"
const server = new Server(
{ name: "my-cli-mcp", version: "1.0.0" },
{ capabilities: {} },
)
// Mount CLI commands as tools alongside your own
addCliToolsToMcp({ cli, server })
const transport = new StdioServerTransport()
await server.connect(transport)
此外,与高级别 McpServer数字 :
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"
const mcp = new McpServer({ name: "my-cli-mcp", version: "1.0.0" })
mcp.tool("custom-tool", "A tool defined directly", async () => ({ ... }))
addCliToolsToMcp({ cli, server: mcp })
HTTP 上的多租户远程 MCP
当你暴露一个cli作为一个 远程 MCP over HTTP,一个进程处理许多同时存在的用户. 每个请求都必须与该用户自己的文件系统,工作目录,环境,和stdin相违背——否则租户会看到对方的状态和stdio写作践踏JSON-RPC频道.
执行 没有 保存 MCP 会话ID 。 可流式 HTTP 运行 无国籍人数字 : sessionIdGenerator: undefined。每个 POST 构建新的 Server 然后把他们关起来。 这对Cloudflare Workers和任何其他不保存过程记忆的隔离都有效.
食谱是:
- 定义 cli 一次。 。 。 .
- 打开 每个后,从请求中解决租户(JWT, cookie, header), 克隆 阴道
{ cwd, env, fs }并把它挂在新鲜的上Server通过addCliToolsToMcp({ cli: tenantClone, server })。 。 。 . - 内部命令动作,总是使用 已注射
ctx—— 说ctx.fs, (中文(简体) ),ctx.process.cwd, (中文(简体) ),ctx.process.env, (中文(简体) ),ctx.console.log——取而代之的是节点全球.@goke/mcp将每个工具调用到租户的克隆语境中,但只有通过代码ctx参与这种孤立.
写入命令反对 ctx
import { goke } from "goke"
import { z } from "zod"
import path from "node:path"
const cli = goke("notes-app")
cli
.command("save <filename>", "Save content into the user's workspace")
.option("--content <content>", z.string().describe("File content"))
.action(async (filename, options, ctx) => {
const full = path.posix.join(ctx.process.cwd, filename)
await ctx.fs.writeFile(full, options.content)
return { saved: full, tenant: ctx.process.env.TENANT_ID }
})
cli
.command("load <filename>", "Load a file from the user's workspace")
.action(async (filename, _options, ctx) => {
const full = path.posix.join(ctx.process.cwd, filename)
const text = await ctx.fs.readFile(full, "utf8")
return { path: full, text }
})
ctx.fs 满足 GokeFs 界面 – 一个可兼容节点文件系统 API。 您可以将其指向一个真实的目录,一个虚拟的内存商店,一个S3桶适配器,一个 memfs,或者任何你能包裹在界面后面的东西.
按请求砍掉克力
MCP SDK号舰 WebStandardStreamableHTTPServerTransport,它接受网络标准 Request 返回 a Response。这个形状直接插入 任意 讲网络标准的网络框架: 香料流动, Cloudflare Workers, Deno, Bun, Next.js 路由处理器, SvelteKit 端点, 或原始 fetch- 基于处理器。 没有快车,没有 node:http 接线,没有框架锁定.
过 sessionIdGenerator: undefined 因此,运输不发射或预期 mcp-session-id不将运输存储于 Map. JSON-RPC initialize, (中文(简体) ), tools/list,以及 tools/call 它们是独立的POST。 每个人从请求的租户身份中复制出cli.
这是 MCP SDK v1 流式 HTTP 没有可选的运输会议 (议定书修订至 2025-11-25) (中文(简体) ). 不是后来 2026-07-28 协议, 放弃 initialize。会话ID是可选的 2025-11-25. 无国籍服务器省略.
可流 HTTP 光谱要求 来源 检查每个请求(DNA重新绑定)。 拒绝礼物, 拒绝 Origin 与 403 (韩语)缺少 Origin 对非浏览器 MCP 客户端来说是正常的.
POST /mcp (JWT / x-tenant-id)
│
v
resolveTenant(id) ──> baseCli.clone({ cwd, env, fs })
│
v
fresh Server + transport
sessionIdGenerator: undefined
│
v
addCliToolsToMcp ──> handleRequest
│
v
Response
│
v
close transport + server ──> nothing stored
你造一个 handleMcpRequest(request: Request): Promise<Response> 函数并挂载 HTTP 路径 :
import { Server as McpServer } from "@modelcontextprotocol/sdk/server/index.js"
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js"
import { addCliToolsToMcp } from "@goke/mcp"
import type { GokeFs } from "goke"
declare function resolveTenant(tenantId: string): {
cwd: string
env: Record<string, string>
fs: GokeFs
}
declare function isAllowedOrigin(origin: string): boolean
export async function handleMcpRequest(request: Request): Promise<Response> {
const origin = request.headers.get("origin")
if (origin && !isAllowedOrigin(origin)) {
return new Response(null, { status: 403 })
}
if (request.method !== "POST") {
return new Response(null, { status: 405, headers: { Allow: "POST" } })
}
const parsedBody = await request.clone().json().catch(() => undefined)
const tenantId = request.headers.get("x-tenant-id")
if (!tenantId) return new Response("missing x-tenant-id", { status: 401 })
const tenant = resolveTenant(tenantId)
const tenantCli = baseCli.clone({
cwd: tenant.cwd,
env: { ...tenant.env, TENANT_ID: tenantId },
fs: tenant.fs,
})
const mcpServer = new McpServer(
{ name: "notes-app-mcp", version: "1.0.0" },
{ capabilities: {} },
)
addCliToolsToMcp({ cli: tenantCli, server: mcpServer })
const transport = new WebStandardStreamableHTTPServerTransport({
sessionIdGenerator: undefined,
enableJsonResponse: true,
})
await mcpServer.connect(transport)
try {
return await transport.handleRequest(request, { parsedBody })
} finally {
await transport.close()
await mcpServer.close()
}
}
现在插上 handleMcpRequest 进入您使用的网络运行时间 :
// Spiceflow — runs on Node, Bun, and Cloudflare Workers with the same code
import { Spiceflow } from "spiceflow"
export const app = new Spiceflow()
.route({
method: "*",
path: "/mcp",
handler: ({ request }) => handleMcpRequest(request),
})
app.listen(3000)
// Cloudflare Workers / Deno / Bun
export default {
async fetch(request: Request): Promise<Response> {
const url = new URL(request.url)
if (url.pathname === "/mcp") return handleMcpRequest(request)
return new Response("not found", { status: 404 })
},
}
// Next.js app router
export async function POST(request: Request) {
return handleMcpRequest(request)
}
关键保障
- 每个请求都反对
tenantCli是因为cwd编号 :env编号 :fs不是基地的cli 不是另一个租户的. ctx.console.log编号 :ctx.console.error编号 :ctx.process.stdout.write编号 :ctx.process.stderr.write被俘虏到CallToolResult.content. 它们从未到达主机进程 stdio,所以它们不能腐蚀JSON-RPC频道或者在用户之间泄露.ctx.process.exit(code)掷出GokeProcessExit而不是杀死服务器。 工具调用决定为{ isError: code !== 0, content: [captured output] }而下一个请求继续运行.- 行动
throw被捕获并返回为{ isError: true, content: [message, stderr] }。 。 。 .
附带危险
只有代码流经 ctx 参与隔离。 以下内容: 绕行 并会泄漏到租户之间 或杀死东道主的过程:
import fs from "node:fs"在命令动作中——读取/写入真实的磁盘.console.log(...)编号 :console.error(...)写给真正的服务器 stdio.process.exit(1)——终止整个主机进程.process.cwd()编号 :process.env.X在模块加载时间——快照服务器的值,而不是租户的值.
将其移植到 ctx.fs, (中文(简体) ), ctx.console, (中文(简体) ), ctx.process.* 而你是多租户安全.
对于一个可运行的端到端实例(包括两个同时撰写单独文件的内存租户,每个POST有一个新的服务器),参见 src/__test__/http-multi-tenant.test.ts。 。 。 .
下层原始 : cli.createExecutionContext(override)
如果你正在建造自定义的运输工具或非HTTP多租位适配器,潜在的goke原始是:
import { GokeProcessExit, type GokeExecutionContextOverride } from "goke"
const override: GokeExecutionContextOverride = {
cwd: tenant.cwd,
env: tenant.env,
fs: tenant.fs,
stdin: tenant.stdin,
stdout: captureStdoutStream,
stderr: captureStderrStream,
exit: () => {}, // throw-only: the wrapper still throws GokeProcessExit
}
const ctx = cli.createExecutionContext(override)
try {
await action(...positionalArgs, options, ctx)
} catch (err) {
if (err instanceof GokeProcessExit) {
// handle the exit code — the host process is untouched
} else {
throw err
}
}
addCliToolsToMcp 在每一个工具调用上为您构建此背景 。 需要更精细控制(例如,每个请求抓取自定义路由的流,合成)的,你自己叫它 argv,或从执行的非节点运行时间提供 MCP GokeFs (见a/cn.9/wg.iii/wp.iii/wp.1号文件).
完整实例( 有配置持续)
此图案用于 概念- mcp- cli数字 :
import { goke } from 'goke'
import { addMcpCommands } from '@goke/mcp'
import type { McpOAuthState, CachedMcpTools } from '@goke/mcp'
import fs from 'node:fs'
import path from 'node:path'
import os from 'node:os'
// --- Config persistence (JSON file in ~/.myapp/) ---
const CONFIG_DIR = path.join(os.homedir(), '.myapp')
const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json')
interface AppConfig {
mcpUrl: string
oauthState?: McpOAuthState
cache?: CachedMcpTools
}
function loadConfig(): AppConfig {
try {
return JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf-8'))
} catch {
return { mcpUrl: 'https://mcp.notion.com/mcp' }
}
}
function saveConfig(partial: Partial<AppConfig>): void {
const merged = { ...loadConfig(), ...partial }
fs.mkdirSync(CONFIG_DIR, { recursive: true })
fs.writeFileSync(CONFIG_FILE, JSON.stringify(merged, null, 2))
}
// --- CLI setup ---
const cli = goke('myapp')
await addMcpCommands({
cli,
clientName: 'myapp',
getMcpUrl: () => loadConfig().mcpUrl,
oauth: {
clientName: 'My App',
load: () => loadConfig().oauthState,
save: (state) => saveConfig({ oauthState: state }),
},
loadCache: () => loadConfig().cache,
saveCache: (cache) => saveConfig({ cache }),
})
// Custom commands alongside auto-generated MCP commands
cli
.command('login', 'Save MCP URL')
.option('--url <url>', 'MCP server URL')
.action((options) => {
saveConfig({ mcpUrl: options.url })
console.log(`Saved: ${options.url}`)
})
cli.command('logout', 'Clear tokens').action(() => {
saveConfig({ oauthState: undefined, cache: undefined })
console.log('Logged out')
})
cli.help()
cli.completions()
cli.parse()
API 密码
addMcpCommands(options)
在 goke CLI 实例上注册 MCP 工具命令 .
| 选项 | 类型 | 默认 | 说明 |
|---|---|---|---|
cli | Goke | 所需经费 | 要添加命令的去ke CLI 实例 |
getMcpUrl | () => string | undefined | —— 说 | 返回 MCP 服务器 URL。 返回 URL , 即使用户没有登录 --help 还行 |
getMcpTransport | () => Transport | null | —— 说 | 定制运输. 用于stdio或任何东西 getMcpUrl 无法表达 |
getHeaders | () => Record<string, string> | undefined | —— 说 | 额外的 HTTP 信头( 例如) Authorization) (中文(简体) ). 使用过的 getMcpUrl |
argv | string[] | process.argv.slice(2) | 在帮助上跳过现场发现和已经注册的命令的参数 |
commandPrefix | string | '' | 命令的前缀( 例如 ). 'mcp' 制造 mcp notion-search(中文(简体) ) |
clientName | string | 'mcp-cli-client' | 连接时发送到 MCP 服务器的名称 |
oauth | McpOAuthConfig | —— 说 | 需要认证的服务器的 OAuth 配置 |
loadCache | () => CachedMcpTools | undefined | 所需经费 | 从存储中装入缓存工具 |
saveCache | (cache) => void | 所需经费 | 保存缓存工具到存储 |
McpOAuthConfig
| 外地 | 类型 | 说明 |
|---|---|---|
clientName | string | OAuth 同意屏幕上显示的名称 |
load | () => McpOAuthState | undefined | 装入持续 OAuth 状态 |
save | (state) => void | 在 认证或令牌刷新后保存 OAuth 状态 |
onAuthUrl | (url: string) => void | Auth URL 自定义处理器( 默认: 打开浏览器) |
onAuthSuccess | () => void | 在成功认证后调用 |
onAuthError | (error: string) => void | 调用认证失败 |
出口
// MCP server → CLI (consume MCP tools as CLI commands)
export { addMcpCommands } from '@goke/mcp'
export type { AddMcpCommandsOptions, CachedMcpTools } from '@goke/mcp'
export type { McpOAuthConfig, McpOAuthState } from '@goke/mcp'
// CLI → MCP server (expose CLI commands as MCP tools)
export { createMcpAction, addCliToolsToMcp } from '@goke/mcp'
export type { CreateMcpActionOptions, AddCliToolsToMcpOptions } from '@goke/mcp'
OA 流量
奥奥特是 懒惰 启动时不进行认证检查 。 流动是:
User runs command
│
▼
Call MCP tool ───── success ──▸ Print result
│
401 error
│
▼
Start local server (random port)
│
▼
Open browser ──▸ User authorizes
│
▼
Receive callback with auth code
│
▼
Exchange code for tokens
│
▼
Save tokens via oauth.save()
│
▼
Retry the original tool call
拳头通过 oauth.save() 调回您提供的调回, 因此后续运行会全部跳过 auth .
缓存
工具计划缓存 1小时 这样 --help 并且命令注册不会在每次引用时击中网络。 缓存是通过 loadCache编号 :saveCache 召回电话。 您控制它存储的位置( 文件、 数据库、 env等) 。 每个工具呼叫仍然打开一个新的MCP连接. 没有 Mcp-Session-Id 复用相会.
当缓存过期或一个工具呼叫失败时,缓存被清除,工具在下次运行时被重排.
如果活着 tools/list 无法运行( 无运输, 401 期间) --help, (中文(简体) ), addMcpCommands 仍然从过期缓存中注册工具, 帮助仍然有用 .
许可证
麻省理工学院