简易mcp
EasyMCP可用,但处于测试阶段。请报告您遇到的任何问题。
EasyMCP是在TypeScript中创建模型上下文协议(MCP)服务器的最简单方法。
它将管道、格式和其他样板定义隐藏在简单的声明后面。
Easy MCP允许您定义入门所需的最低限度。或者,您可以定义更复杂的资源、模板、工具和提示。
特性
- 类似简单表达式的API:EasyMCP提供了一个高级、直观的API。使用类似于在ExpressJS中定义端点的调用来定义工具、提示、资源、资源模板和根。每个可能是可选的参数都是可选的,除非你需要,否则都是隐藏的。
- 实验装饰师API:自动推断工具、提示和资源参数。不需要输入架构定义!
- 上下文对象:通过工具中的上下文对象访问MCP功能,如日志记录和进度报告。
- 出色的类型安全性:更好的DX和更少的运行时错误。
Beta限制
- 尚不支持MCP采样
- 尚未支持SSE
- 尚未收到资源更新通知
- 提示在技术上接受输入,但Typescript SDK建议他们不能。因此,这个功能感觉还没有完成。
安装
要安装EasyMCP,请在项目目录中运行以下命令:
bun install快速入门(实验)装饰API
另请参阅 examples/express-decorators.ts 或奔跑 bun start:decorators
EasyMCP的decorator API非常简单,可以自动推断类型和输入配置。
但它是 *实验性的* 并且可能改变或尚未发现问题。
import EasyMCP from "./lib/EasyMCP";
import { Tool, Resource, Prompt } from "./lib/experimental/decorators";
class MyMCP extends EasyMCP {
@Resource("greeting/{name}")
getGreeting(name: string) {
return `Hello, ${name}!`;
}
@Prompt()
greetingPrompt(name: string) {
return `Generate a greeting for ${name}.`;
}
@Tool()
greet(name: string, optionalContextFromServer: Context) {
optionalContextFromServer.info(`Greeting ${name}`);
return `Hello, ${name}!`;
}
}
const mcp = new MyMCP({ version: "1.0.0" });装饰器API的复杂示例
看 examples/express-express.ts 或奔跑 bun start:express
import EasyMCP from "./lib/EasyMCP";
import { Prompt } from "./lib/decorators/Prompt";
import { Resource } from "./lib/decorators/Resource";
import { Root } from "./lib/decorators/Root";
import { Tool } from "./lib/decorators/Tool";
@Root("/my-sample-dir/photos")
@Root("/my-root-dir", { name: "My laptop's root directory" }) // Optionally you can name the root
class ZachsMCP extends EasyMCP {
/**
You can declare a Tool with zero configuration. Relevant types and plumbing will be inferred and handled.
By default, the name of the Tool will be the name of the method.
*/
@Tool()
simpleFunc(nickname: string, height: number) {
return `${nickname} of ${height} height`;
}
/**
* You can enhance a tool with optional data like a description.
Due to limitations in Typescript, if you want the Tool to serialize certain inputs as optional to the Client, you need to provide an optionals list.
*/
@Tool({
description: "An optional description",
optionals: ["active", "items", "age"],
})
middleFunc(name: string, active?: string, items?: string[], age?: number) {
return `exampleFunc called: name ${name}, active ${active}, items ${items}, age ${age}`;
}
/**
* You can also provide a schema for the input arguments of a tool, if you want full control.
*/
@Tool({
description: "A function with various parameter types",
parameters: [
{
name: "date",
type: "string",
optional: false,
},
{
name: "season",
type: "string",
optional: false,
},
{
name: "year",
type: "number",
optional: true,
},
],
})
complexTool(date: string, season: string, year?: number) {
return `complexTool called: date ${date}, season ${season}, year ${year}`;
}
/**
* Tools can use a context object to access MCP capabilities like logging, progress reporting, and meta data from the request
*/
@Tool({
description: "A tool that uses context",
})
async processData(dataSource: string, context: Context) {
context.info(`Starting to process data from ${dataSource}`);
try {
const data = await context.readResource(dataSource);
context.debug("Data loaded");
for (let i = 0; i setTimeout(resolve, 1000));
await context.reportProgress(i * 20, 100);
context.info(`Processing step ${i + 1} complete`);
}
return `Processed ${data.length} bytes of data from ${dataSource}`;
} catch (error) {
context.error(`Error processing data: ${(error as Error).message}`);
throw error;
}
}
/**
* Resources can be declared with a simple URI.
By default, the name of the resource will be the name of the method.
*/
@Resource("simple-resource")
simpleResource() {
return "Hello, world!";
}
/**
* Or include handlebars which EasyMCP will treat as a Resource Template.
Both Resources and Resource Templates can be configured with optional data like a description.
*/
@Resource("greeting/{name}")
myResourceTemplate(name: string) {
return `Hello, ${name}!`;
}
/**
* By default, prompts need no configuration.
They will be named after the method they decorate.
*/
@Prompt()
simplePrompt(name: string) {
return `Prompting... ${name}`;
}
/**
* Or you can override and configure a Prompt with a name, description, and explicit arguments.
*/
@Prompt({
name: "configured-prompt",
description: "A prompt with a name and description",
args: [
{
name: "name",
description: "The name of the thing to prompt",
required: true,
},
],
})
configuredPrompt(name: string) {
return `Prompting... ${name}`;
}
}
const mcp = new ZachsMCP({ version: "1.0.0" });
console.log(mcp.name, "is now serving!");
使用Express-like API快速入门
另请参阅 examples/example-minimal.ts 或奔跑 bun start:express
这个API更详细,也不那么神奇,但它更稳定,更经过测试。
import EasyMCP from "easy-mcp";
const mcp = EasyMCP.create("my-mcp-server", {
version: "0.1.0",
});
// Define a resource
mcp.resource({
uri: "dir://desktop",
name: "Desktop Directory", // Optional
description: "Lists files on the desktop", // Optional
mimeType: "text/plain", // Optional
fn: async () => {
return "file://desktop/file1.txt\nfile://desktop/file2.txt";
},
});
// Define a resource template
mcp.template({
uriTemplate: "file://{filename}",
name: "File Template", // Optional
description: "Template for accessing files", // Optional
mimeType: "text/plain", // Optional
fn: async ({ filename }) => {
return `Contents of ${filename}`;
},
});
// Define a tool
mcp.tool({
name: "greet",
description: "Greets a person", // Optional
inputs: [ // Optional
{
name: "name",
type: "string",
description: "The name to greet",
required: true,
},
],
fn: async ({ name }) => {
return `Hello, ${name}!`;
},
});
// Define a prompt
mcp.prompt({
name: "introduction",
description: "Generates an introduction", // Optional
args: [ // Optional
{
name: "name",
type: "string",
description: "Your name",
required: true,
},
],
fn: async ({ name }) => {
return `Hi there! My name is ${name}. It's nice to meet you!`;
},
});
// Start the server
mcp.serve().catch(console.error);类似Express-Like API
EasyMCP.create(name: string, options: ServerOptions)
创建新的EasyMCP实例。
name:您的MCP服务器的名称。options:服务器选项,包括版本。
mcp.resource(config: ResourceConfig)
定义资源。
mcp.template(config: ResourceTemplateConfig)
定义资源模板。
mcp.tool(config: ToolConfig)
定义工具。
mcp.prompt(config: PromptConfig)
定义提示。
mcp.root(config: Root)
定义根。
mcp.serve()
启动MCP服务器。
(实验)装饰师API
EasyMCP提供了一种更简洁和声明性的方式来定义MCP服务器组件的装饰器。以下是可用装饰器的概述:
@Tool(config?: ToolConfig)
将方法定义为工具。该方法将接受您声明的任何参数,并根据TS注释推断类型和输入配置。可选 context 参数可以添加为访问MCP功能的最后一个参数。
config:工具的可选配置对象。
- description:工具的可选描述。 - optionals:应标记为可选的参数名称的可选数组。 - parameters:用于完全控制输入架构的可选参数定义数组。
例子:
@Tool({
description: "Greets a person",
optionals: ["title"],
})
greet(name: string, title?: string, optionalContext: Context) {
return `Hello, ${title ? title + " " : ""}${name}!`;
}@Resource(uri: string, config?: Partial)
将方法定义为资源或资源模板。资源模板是通过在URI中使用handlebars来定义的。
uri:资源的URI或URI模板。config:资源的可选配置对象。
- name:资源的可选名称。 - description:资源的可选描述。 - mimeType:资源的可选MIME类型。
例子:
@Resource("greeting/{name}")
getGreeting(name: string) {
return `Hello, ${name}!`;
}@Prompt(config?: PromptDefinition)
将方法定义为提示。
config:提示的可选配置对象。
- name:提示的可选名称(默认为方法名)。 - description:提示的可选描述。 - args:参数定义的可选数组。
例子:
@Prompt({
description: "Generates a greeting prompt",
args: [
{ name: "name", description: "Name to greet", required: true },
],
})
greetingPrompt(name: string) {
return `Generate a friendly greeting for ${name}.`;
}@Root(uri: string, config?: { name?: string })
定义MCP服务器的根目录。这个装饰器应用于类,而不是方法。
uri:根目录的URI。config:可选配置对象。
- name:根的可选名称。
例子:
@Root("/my-sample-dir/photos")
@Root("/my-root-dir", { name: "My laptop's root directory" })
class MyMCP extends EasyMCP {
// ...
}使用装饰器时,EasyMCP将自动推断类型,并为您的工具、资源、提示和根创建适当的配置。这可以显著减少样板代码,使您的MCP服务器定义更加简洁。
但是。..装饰器API是实验性的,可能会有错误或意外的更改
贡献
欢迎投稿!只需提交一份PR。
许可证
该项目根据MIT许可证获得许可。

