完成 SDK 部分的文档编写

This commit is contained in:
锦恢 2025-06-22 19:43:50 +08:00
parent ecfa70bda2
commit 8acb53ff54
35 changed files with 869 additions and 19 deletions

View File

@ -150,17 +150,27 @@ export default {
],
'/sdk-tutorial/': [
{
text: 'Overview',
text: 'Introduction',
items: [
{ text: 'openmcpsdk.js', link: '/sdk-tutorial/' }
{ text: 'openmcp-sdk', link: '/sdk-tutorial/' },
{ text: 'Installation', link: '/sdk-tutorial/install' },
]
},
{
text: 'Basic Usage',
items: [
{ text: 'Simplest Conversation', link: '/sdk-tutorial/usage/greet' },
{ text: 'Task Loop', link: '/sdk-tutorial/usage/task-loop' },
{ text: 'Multiple Server Connections', link: '/sdk-tutorial/usage/multi-server' }
{ text: 'Simple Chat', link: '/sdk-tutorial/usage/basic' },
{ text: 'Multi-turn Conversation', link: '/sdk-tutorial/usage/send-multi-message' },
{ text: 'Setting Parameters', link: '/sdk-tutorial/usage/setting' },
]
},
{
text: 'MCP',
items: [
{ text: 'Quick Deployment', link: '/sdk-tutorial/usage/fast-deploy' },
{ text: 'Task Loop Control', link: '/sdk-tutorial/usage/task-loop' },
{ text: 'Connect Multiple MCP Servers', link: '/sdk-tutorial/usage/multi-server' },
{ text: 'Human-in-the-Loop (HIL)', link: '/sdk-tutorial/usage/hil' },
]
}
]

View File

@ -149,17 +149,27 @@ export default {
],
'/ja/sdk-tutorial/': [
{
text: '概要',
text: 'はじめに',
items: [
{ text: 'openmcpsdk.js', link: '/ja/sdk-tutorial/' }
{ text: 'openmcp-sdk', link: '/ja/sdk-tutorial/' },
{ text: 'インストール', link: '/ja/sdk-tutorial/install' },
]
},
{
text: '基本的な使い方',
text: '基本操作',
items: [
{ text: '最もシンプルな会話', link: '/ja/sdk-tutorial/usage/greet' },
{ text: 'タスクループ', link: '/ja/sdk-tutorial/usage/task-loop' },
{ text: '複数サーバー接続', link: '/ja/sdk-tutorial/usage/multi-server' }
{ text: '簡単な会話', link: '/ja/sdk-tutorial/usage/basic' },
{ text: 'マルチターン会話', link: '/ja/sdk-tutorial/usage/send-multi-message' },
{ text: 'パラメータ設定', link: '/ja/sdk-tutorial/usage/setting' },
]
},
{
text: 'MCP',
items: [
{ text: 'クイックデプロイ', link: '/ja/sdk-tutorial/usage/fast-deploy' },
{ text: 'タスクループ制御', link: '/ja/sdk-tutorial/usage/task-loop' },
{ text: '複数MCPサーバー接続', link: '/ja/sdk-tutorial/usage/multi-server' },
{ text: 'ヒューマン・イン・ザ・ループ (HIL)', link: '/ja/sdk-tutorial/usage/hil' },
]
}
]

View File

@ -151,15 +151,25 @@ export default {
{
text: '简介',
items: [
{ text: 'openmcpsdk.js', link: '/zh/sdk-tutorial/' },
{ text: 'openmcpsdk', link: '/zh/sdk-tutorial/' },
{ text: '安装', link: '/zh/sdk-tutorial/install' },
]
},
{
text: '基本使用',
items: [
{ text: '最简单的对话', link: '/zh/sdk-tutorial/usage/greet' },
{ text: '任务循环', link: '/zh/sdk-tutorial/usage/task-loop' },
{ text: '多服务器连接', link: '/zh/sdk-tutorial/usage/multi-server' },
{ text: '最简单的对话', link: '/zh/sdk-tutorial/usage/basic' },
{ text: '多轮对话', link: '/zh/sdk-tutorial/usage/send-multi-message' },
{ text: '设置对话参数', link: '/zh/sdk-tutorial/usage/setting' },
]
},
{
text: 'MCP',
items: [
{ text: '极速部署', link: '/zh/sdk-tutorial/usage/fast-deploy' },
{ text: '任务循环的控制', link: '/zh/sdk-tutorial/usage/task-loop' },
{ text: '连接多个 MCP 服务器', link: '/zh/sdk-tutorial/usage/multi-server' },
{ text: '人机交互', link: '/zh/sdk-tutorial/usage/hil' },
]
}
]

View File

@ -0,0 +1,24 @@
# インストール
openmcp-sdkは現在ESMビルドのみをサポートしています。そのため、インストール前にESM開発環境を準備してください:
```bash
mkdir clever-agent && cd clever-agent
npm init -y
npm install typescript tsx @types/node --save-dev
tsc --init
```
package.jsonで`"type": "module"`を設定することを忘れないでください。
その後、以下のコマンドでopenmcp-sdkをインストールできます:
```bash
npm install openmcp-sdk
```
agentの実行とデプロイにはtsxツールの使用を強く推奨します:
```bash
npx tsx /path/to/agent.ts
```

View File

@ -0,0 +1,68 @@
# 最もシンプルな対話
他のすべてのAgentフレームワークと同様に、openmcp-sdkを使用して大規模言語モデルとの最も基本的なテキスト対話を実現できます。これはわずか数行のコードで簡単に完了します。
## agentの作成
openmcp-sdkでは以下の文で迅速にagentインスタンスを作成できます
```typescript
import { OmAgent } from 'openmcp-sdk/service/sdk';
const agent = new OmAgent();
```
これは私たちの後続作業すべての基礎となります。
## 大規模言語モデルの設定
`setDefaultLLM`を使用してデフォルトの大規模言語モデルを設定できます。ここではdeepseekを例に挙げます
```typescript
agent.setDefaultLLM({
baseURL: 'https://api.deepseek.com',
apiToken: 'sk-xxxxxxxxxxxxxxxx',
model: 'deepseek-chat',
});
```
:::tip
APIキーがコード内に存在することで漏洩するのを防ぐため、環境変数からの入力を推奨します
bashrcまたはzshrcファイルに以下を追加
```bash
export OPENMCP_API_TOKEN=sk-xxxxxxxxxxxxxxxx
```
そして上記コードを修正:
```typescript
agent.setDefaultLLM({
baseURL: 'https://api.deepseek.com',
apiToken: process.env['OPENMCP_API_TOKEN'],
model: 'deepseek-chat',
});
```
:::
その他の大規模言語モデルの接続パラメータについては、各モデル提供元のドキュメントを参照してください。
## 対話の送信
`ainvoke`メソッドを使用して、テキストを直接大規模言語モデルに送信し、1回のインタラクションと対話を完了できます
```typescript
const result = await agent.ainvoke({ messages: '你好,我是 LSTM-Kirigaya我的另一个名字是锦恢' });
console.log(result)
```
上記のコードを実行すると、以下のような返答が得られます:
```
你好LSTM-Kirigaya锦恢很高兴认识你
你的名字结合了技术LSTM长短期记忆网络和动漫元素Kirigaya可能让人联想到《刀剑神域》的桐谷和人/桐人而“锦恢”这个中文名又很有诗意听起来像是一位对AI和二次元都充满热情的伙伴呢
有什么想聊的吗无论是技术、ACG还是名字背后的故事我都乐意倾听
```

View File

@ -0,0 +1,37 @@
# 迅速なデプロイ
openmcp-sdkのコア機能の1つは迅速なデプロイです。openmcp-clientとの連携を活用することで、MCP Agentのデプロイをわずか10秒で完了できます。
## 1. openmcpからmcpconfig.jsonをエクスポートする
まず、openmcpでデバッグ済みのmcpプロジェクトを開きます。インタラクティブテストで満足のいくデバッグ結果が得られていると仮定します。
ダイアログツールバーの一番右にあるロケットのようなアイコンをクリックすると、次のようなウィンドウが表示されます:
![](./images/export-config.png)
コピーまたはエクスポートをクリックすると、mcpconfig.jsonファイルを取得できます。
## 2. openmcp-sdkにデプロイする
次に、main.tsファイルを作成し、以下の数行のコードで上記の設定をagentとしてデプロイできます:
```typescript
import { OmAgent } from 'openmcp-sdk/service/sdk';
const agent = new OmAgent();
agent.loadMcpConfig('./mcpconfig.json');
const res = await agent.ainvoke({ messages: '今天杭州的天气是什么样子的?' });
console.log('⚙️ Agent Response', res);
```
`npx tsx main.ts`を使用して実行すると、次の結果が得られます:
```
[2025/6/22 19:05:08] 🚀 [SimpleMcpServer] 1.9.2 connected
[2025/6/22 19:05:11] 🤖 Agent wants to use these tools weather
[2025/6/22 19:05:11] 🔧 using tool weather
[2025/6/22 19:05:11] ✓ use tools success
⚙️ Agent Response 今天杭州的天气是小雨气温为24.7°C湿度为95%空气质量指数AQI为26空气质量良好。
```

View File

@ -0,0 +1,6 @@
# ヒューマン・マシン・インタラクション
openmcp-sdkは強力なHILHuman-in-the-Loopワークフローをサポートしており、自動化プロセスの任意の段階で人的介入を可能にします。この機能は大規模言語モデルLLM駆動のアプリケーションで特に有用です。なぜなら、このようなモデルの出力は検証、修正、またはコンテキスト情報の補足が必要となる場合があるためです。
// 続く...

Binary file not shown.

After

Width:  |  Height:  |  Size: 163 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

View File

@ -0,0 +1,28 @@
# 複数のMCPサーババーに接続
openmcp-sdkでは、1つのエージェントで複数のmcpサーバーに同時接続するための2つの方法を提供しています。
## 方法1: mcpconfig.json (推奨)
openmcpプラグインでは、以下のパネルから複数のmcpサーバーに接続してテストできます
![](./images/openmcp-multi-server.png)
その後、[高速デプロイ](./fast-deploy.md)の手順に従ってエクスポートすると、SDKが自動的にこれらの複数サーバーに接続します。
## 方法2: addMcpServer
以下のコードを使用して、エージェントに複数のmcpサーバーを追加することもできます:
```typescript
agent.addMcpServer({
connectionType: 'STDIO',
commandString: 'uv run main.py',
cwd: '/path/to/workspace',
});
agent.addMcpServer({
connectionType: 'STREAMABLE_HTTP',
url: 'go run /path/to/main.go',
});
```

View File

@ -0,0 +1,24 @@
# マルチターン会話の送信
より細かく会話のコンテキストを制御したい場合、`ainvoke`メソッドに配列を渡すことができます:
```typescript
import { AssistantMessage, UserMessage } from 'openmcp-sdk/service/sdk';
const messages = [
UserMessage('私は今日とても美味しい鶏鳴湯包を食べました'),
AssistantMessage('はい、覚えました'),
UserMessage('今日私は何を食べたか覚えていますか?')
]
const result = await agent.ainvoke({ messages });
console.log(result);
```
上記のコードを実行すると、次のような返答が得られます:
```
これまでの会話記録によると、あなたは今日 **鶏鳴湯包** を食べたと述べており、「とても美味しい」と表現されていましたね!😊
他の類似した美食を推薦したり、この湯包の特別な点について話したりしましょうか?
```

View File

@ -0,0 +1,23 @@
# 会話パラメータの設定
ainvokeの第2引数settingを使用して、会話パラメータを設定できます
```typescript
const messages = [
UserMessage('私は今日とても美味しい鶏の鳴き声スープ入り包子を食べました'),
AssistantMessage('はい、覚えました'),
UserMessage('今日私は何を食べたか教えてください')
]
const result = await agent.ainvoke({
messages: messages,
settings: {
systemPrompt: 'あなたはとても親切なアシスタントです',
temperature: 0.7,
// ...
}
});
console.log(result);
```
その他のパラメータはMCP関連の高度な使用方法に関わり、今後のドキュメントで説明されます。

View File

@ -0,0 +1,57 @@
# タスクループ
openmcp-sdkはタスクループのメカニズムでagentを構築し、ユーザーがそれと対話できるようにしています。ユーザーがこのタスクループをリアルタイムで制御する必要がある場合、openmcp-sdkが提供するイベントを通じて対応するフック関数を登録することで実現できます。
[クイックデプロイ](./fast-deploy.md)の例を挙げると、以下のコードでタスクループを制御するオブジェクトを取得できます:
```typescript
import { OmAgent } from '../openmcp-sdk/service/sdk';
const agent = new OmAgent();
agent.loadMcpConfig('./mcpconfig.json');
const loop = await agent.getLoop();
```
:::warning
フックの登録とloopの取得は`agent.ainvoke`を実行する前に完了させる必要があります!
:::
この`loop`オブジェクトを通じて、以下のフックを登録できます:
- `registerOnChunk`: モデルがchunkを返した時にトリガー
- `registerOnDone`: タスク完了時にトリガー
- `registerOnError`: タスクエラー時にトリガー
- `registerOnEpoch`: 各タスクエポック開始時にトリガー
- `registerOnToolCall`: ツール関数呼び出し前にトリガー
- `registerOnToolCalled`: ツール関数呼び出し後にトリガー
これらのフック関数はコールバック関数を受け取り、対応するイベント発生時に呼び出されます。
```typescript
loop.registerOnChunk((chunk) => {
console.log('⚙️ Agent Chunk', chunk);
});
loop.registerOnDone(() => {
console.log('⚙️ Agent Done');
});
loop.registerOnError((err) => {
console.log('⚙️ Agent Error', err);
});
loop.registerOnEpoch(() => {
console.log('⚙️ Agent Epoch');
});
loop.registerOnToolCall((toolCall) => {
console.log('⚙️ Agent Tool Call', toolCall);
return toolCall;
});
loop.registerOnToolCalled((toolCalled) => {
console.log('⚙️ Agent Tool Called', toolCalled);
return toolCalled;
});
```

View File

@ -21,17 +21,30 @@ const client = new OpenAI({
baseURL: 'https://api.deepseek.com/v1'
});
const log = await git.log({n: 1});
const log = await git.log({ n: 1 });
const lastCommitMessage = log.latest.hash;
const pipe = new OmPipe('translate-docs:' + lastCommitMessage.toString());
export async function getChangedFiles(dirPath) {
const status = await git.status();
const changedFiles = [
...status.not_added,
...status.modified,
...status.created
].filter(file => file.startsWith(dirPath));
return new Set(changedFiles.map(file => path.resolve(file)));
}
const filesNeedToTranslate = await getChangedFiles('zh');
async function translateText(text, targetLangID) {
const prompt = `将以下内容准确翻译为ISO编码为 ${targetLangID} 的语言。请严格遵循以下要求翻译内容:
1. 不要添加任何解释说明或额外文本
2. 直接返回翻译后的内容不要包含任何前缀或后缀
需要翻译的内容
${text}`;
${text}`;
const response = await client.chat.completions.create({
model: 'deepseek-chat',
@ -78,7 +91,7 @@ async function traverseAndTranslate(srcDir, destDir, targetLangID) {
console.log(chalk.cyan(`创建目录: ${newDestDir}`));
}
await traverseAndTranslate(fullPath, newDestDir, targetLangID);
} else if (file.endsWith('.md')) {
} else if (filesNeedToTranslate.has(fullPath) && file.endsWith('.md')) {
const destPath = path.join(destDir, file);
// 添加任务
pipe.add('translate:' + destPath, async () => {
@ -96,7 +109,7 @@ const enDir = path.join(__dirname, '..');
console.log(chalk.bold('开始翻译任务'));
await traverseAndTranslate(zhDir, jaDir, 'ja');
// await traverseAndTranslate(zhDir, enDir);
await traverseAndTranslate(zhDir, enDir);
await pipe.start();

24
sdk-tutorial/install.md Normal file
View File

@ -0,0 +1,24 @@
# Installation
Currently, openmcp-sdk only supports esm builds. Therefore, before installation, please set up an esm development environment first:
```bash
mkdir clever-agent && cd clever-agent
npm init -y
npm install typescript tsx @types/node --save-dev
tsc --init
```
Remember to set `"type": "module"` in package.json.
Then you can install openmcp-sdk with the following command:
```bash
npm install openmcp-sdk
```
We highly recommend using the tsx tool to run and deploy your agent:
```bash
npx tsx /path/to/agent.ts
```

View File

@ -0,0 +1,68 @@
# The simplest conversation
Like all other Agent frameworks, you can use openmcp-sdk to accomplish the simplest text interaction with a large model. This can be easily done with just a few lines of code.
## Create agent
openmcp-sdk can quickly create an agent instance with the following statement:
```typescript
import { OmAgent } from 'openmcp-sdk/service/sdk';
const agent = new OmAgent();
```
It is the foundation for all our subsequent work.
## Set up the large model
The default large model can be set via `setDefaultLLM`. Here's an example using deepseek:
```typescript
agent.setDefaultLLM({
baseURL: 'https://api.deepseek.com',
apiToken: 'sk-xxxxxxxxxxxxxxxx',
model: 'deepseek-chat',
});
```
:::tip
To prevent the api key from being exposed in the code, we recommend inputting it via environment variables:
Add the following content to your bashrc or zshrc file:
```bash
export OPENMCP_API_TOKEN=sk-xxxxxxxxxxxxxxxx
```
Then modify the above code:
```typescript
agent.setDefaultLLM({
baseURL: 'https://api.deepseek.com',
apiToken: process.env['OPENMCP_API_TOKEN'],
model: 'deepseek-chat',
});
```
:::
For other large model access parameters, please refer to the documentation of each large model provider.
## Send a conversation
Using the `ainvoke` method, we can directly send text to the large model to complete an interaction and conversation:
```typescript
const result = await agent.ainvoke({ messages: '你好,我是 LSTM-Kirigaya我的另一个名字是锦恢' });
console.log(result)
```
Running the above code, you will get the following reply:
```
你好LSTM-Kirigaya锦恢很高兴认识你
你的名字结合了技术LSTM长短期记忆网络和动漫元素Kirigaya可能让人联想到《刀剑神域》的桐谷和人/桐人而“锦恢”这个中文名又很有诗意听起来像是一位对AI和二次元都充满热情的伙伴呢
有什么想聊的吗无论是技术、ACG还是名字背后的故事我都乐意倾听
```

View File

@ -0,0 +1,37 @@
# Rapid Deployment
One of the core features of openmcp-sdk is rapid deployment. Leveraging its synergy with openmcp-client, you can complete the deployment of an MCP Agent in a lightning-fast 10 seconds.
## 1. Export mcpconfig.json from openmcp
First, open your debugged mcp project in openmcp. Assume you've already achieved satisfactory debugging results during interactive testing.
At this point, click the small rocket-like icon on the far right of the dialog toolbar, and you'll see a window like this:
![](./images/export-config.png)
You can obtain an mcpconfig.json file by clicking either copy or export.
## 2. Deploy to openmcp-sdk
Then we create a file main.ts, deploying the above configuration as an agent with just a few simple lines of code:
```typescript
import { OmAgent } from 'openmcp-sdk/service/sdk';
const agent = new OmAgent();
agent.loadMcpConfig('./mcpconfig.json');
const res = await agent.ainvoke({ messages: 'What is the weather like in Hangzhou today?' });
console.log('⚙️ Agent Response', res);
```
Run it using `npx tsx main.ts`, and you'll get the following result:
```
[2025/6/22 19:05:08] 🚀 [SimpleMcpServer] 1.9.2 connected
[2025/6/22 19:05:11] 🤖 Agent wants to use these tools weather
[2025/6/22 19:05:11] 🔧 using tool weather
[2025/6/22 19:05:11] ✓ use tools success
⚙️ Agent Response The weather in Hangzhou today is light rain, with a temperature of 24.7°C, humidity at 95%, air quality index (AQI) at 26, indicating good air quality.
```

View File

@ -0,0 +1,6 @@
# Human-in-the-Loop
openmcp-sdk supports robust Human-in-the-Loop (HIL) workflows, enabling manual intervention at any stage of the automation process. This feature is particularly useful in applications powered by large language models (LLMs), as the outputs of such models may require verification, correction, or contextual supplementation.
// to be continued ...

Binary file not shown.

After

Width:  |  Height:  |  Size: 163 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

View File

@ -0,0 +1,28 @@
# Connect to Multiple MCP Servers
openmcp-sdk provides two methods to allow you to connect to multiple mcp servers simultaneously on a single agent.
## Method 1: mcpconfig.json (Recommended)
In the openmcp plugin, you can connect to multiple mcp servers and test them using the panel below:
![](./images/openmcp-multi-server.png)
After following the instructions in [Quick Deployment](./fast-deploy.md) to export, the SDK will automatically connect to these multiple servers for you.
## Method 2: addMcpServer
You can also add multiple mcp servers to the agent using the following code:
```typescript
agent.addMcpServer({
connectionType: 'STDIO',
commandString: 'uv run main.py',
cwd: '/path/to/workspace',
});
agent.addMcpServer({
connectionType: 'STREAMABLE_HTTP',
url: 'go run /path/to/main.go',
});
```

View File

@ -0,0 +1,24 @@
# Send Multi-turn Conversation
If you want more granular control over the conversation context, you can pass an array to the `ainvoke` method:
```typescript
import { AssistantMessage, UserMessage } from 'openmcp-sdk/service/sdk';
const messages = [
UserMessage('I just had an amazing bowl of Jiming soup dumplings today'),
AssistantMessage('Got it, Ive made a note'),
UserMessage('Can you recall what I ate today?')
]
const result = await agent.ainvoke({ messages });
console.log(result);
```
Running the above code will give you the following response:
```
Based on our previous conversation, you mentioned having **Jiming soup dumplings** today and described them as "amazing"! 😊
Would you like recommendations for similar dishes or to chat more about what made these dumplings special?
```

View File

@ -0,0 +1,23 @@
# Set Conversation Parameters
You can configure conversation parameters through the `setting` parameter, the second argument of `ainvoke`:
```typescript
const messages = [
UserMessage('I just had an amazing bowl of Jirim Tangbao today'),
AssistantMessage('Got it, Ive memorized that'),
UserMessage('Can you tell me what I ate today?')
]
const result = await agent.ainvoke({
messages: messages,
settings: {
systemPrompt: 'You are a very friendly assistant',
temperature: 0.7,
// ...
}
});
console.log(result);
```
Additional parameters related to advanced MCP usage will be described in subsequent documentation.

View File

@ -0,0 +1,57 @@
# Task Loop
openmcp-sdk builds agents using a task loop mechanism and allows users to interact with them. If users need real-time control over this task loop, they can register corresponding hook functions through the events provided by openmcp-sdk.
Taking the example from [Quick Deployment](./fast-deploy.md), you can obtain the object controlling the task loop with the following code:
```typescript
import { OmAgent } from '../openmcp-sdk/service/sdk';
const agent = new OmAgent();
agent.loadMcpConfig('./mcpconfig.json');
const loop = await agent.getLoop();
```
:::warning
Registering hooks and obtaining the loop must be completed before `agent.ainvoke`!
:::
With this `loop` object, we can register the following hooks:
- `registerOnChunk`: Triggered when the model returns a chunk
- `registerOnDone`: Triggered when the task is completed
- `registerOnError`: Triggered when the task encounters an error
- `registerOnEpoch`: Triggered at the start of each task epoch
- `registerOnToolCall`: Triggered before calling a tool function
- `registerOnToolCalled`: Triggered after calling a tool function
These hook functions accept a callback function, which will be called when the corresponding event is triggered.
```typescript
loop.registerOnChunk((chunk) => {
console.log('⚙️ Agent Chunk', chunk);
});
loop.registerOnDone(() => {
console.log('⚙️ Agent Done');
});
loop.registerOnError((err) => {
console.log('⚙️ Agent Error', err);
});
loop.registerOnEpoch(() => {
console.log('⚙️ Agent Epoch');
});
loop.registerOnToolCall((toolCall) => {
console.log('⚙️ Agent Tool Call', toolCall);
return toolCall;
});
loop.registerOnToolCalled((toolCalled) => {
console.log('⚙️ Agent Tool Called', toolCalled);
return toolCalled;
});
```

View File

@ -0,0 +1,25 @@
# 安装
openmcp-sdk 目前只支持 esm 的构建方式,所以,在安装之前,请先安装一个 esm 的开发环境:
```bash
mkdir clever-agent && cd clever-agent
npm init -y
npm install typescript tsx @types/node --save-dev
tsc --init
```
记得在 package.json 中设置 `"type": "module"`
然后通过下面就可以安装 openmcp-sdk 了:
```bash
npm install openmcp-sdk
```
我们强烈推荐通过 tsx 工具来运行和部署您的 agent
```bash
npx tsx /path/to/agent.ts
```

View File

@ -0,0 +1,70 @@
# 最简单的对话
和其他所有的 Agent 框架一样,你可以利用 openmcp-sdk 完成一个和大模型最简单的文本交互。这只需要几行代码就能轻松完成。
## 创建 agent
openmcp-sdk 通过如下语句可以快速创建一个 agent 实例:
```typescript
import { OmAgent } from 'openmcp-sdk/service/sdk';
const agent = new OmAgent();
```
它是我们后续一切工作的基础。
## 设置大模型
通过 `setDefaultLLM` 可以设置默认的大模型。此处以 deepseek 为例:
```typescript
agent.setDefaultLLM({
baseURL: 'https://api.deepseek.com',
apiToken: 'sk-xxxxxxxxxxxxxxxx',
model: 'deepseek-chat',
});
```
:::tip
为了防止 api key 在代码中,从而泄漏,我们建议通过环境变量来输入:
在您的 bashrc 或者 zshrc 文件中添加如下内容:
```bash
export OPENMCP_API_TOKEN=sk-xxxxxxxxxxxxxxxx
```
然后修改上述代码:
```typescript
agent.setDefaultLLM({
baseURL: 'https://api.deepseek.com',
apiToken: process.env['OPENMCP_API_TOKEN'],
model: 'deepseek-chat',
});
```
:::
其他的大模型接入参数请参考各个大模型厂家自己的文档说明。
## 发送对话
通过 `ainvoke` 方法,我们可以直接把文本发送给大模型完成一次交互和对话:
```typescript
const result = await agent.ainvoke({ messages: '你好,我是 LSTM-Kirigaya我的另一个名字是锦恢' });
console.log(result)
```
运行上面的代码,你会得到如下的回复:
```
你好LSTM-Kirigaya锦恢很高兴认识你
你的名字结合了技术LSTM长短期记忆网络和动漫元素Kirigaya可能让人联想到《刀剑神域》的桐谷和人/桐人而“锦恢”这个中文名又很有诗意听起来像是一位对AI和二次元都充满热情的伙伴呢
有什么想聊的吗无论是技术、ACG还是名字背后的故事我都乐意倾听
```

View File

@ -0,0 +1,38 @@
# 极速部署
openmcp-sdk 的核心特性之一就是极速部署,利用和 openmcp-client 的联动性您可以在短短10秒内闪电般完成 MCP Agent 的部署。
## 1. 从 openmcp 中导出 mcpconfig.json
首先,先在 openmcp 中打开你调试好的 mcp 项目。假设在交互测试中,你已经完成了让您满意的调试结果。
此时,点击对话框工具栏的最右侧一个小火箭一样的图标,你会看到这样的窗口:
![](./images/export-config.png)
点击复制或者导出都可以获得一份 mcpconfig.json 文件。
## 2. 部署到 openmcp-sdk 中
然后我们创建文件 main.ts直接简单几行代码就能把上面的配置部署成一个 agent
```typescript
import { OmAgent } from 'openmcp-sdk/service/sdk';
const agent = new OmAgent();
agent.loadMcpConfig('./mcpconfig.json');
const res = await agent.ainvoke({ messages: '今天杭州的天气是什么样子的?' });
console.log('⚙️ Agent Response', res);
```
使用 `npx tsx main.ts` 运行一下,得到如下结果:
```
[2025/6/22 19:05:08] 🚀 [SimpleMcpServer] 1.9.2 connected
[2025/6/22 19:05:11] 🤖 Agent wants to use these tools weather
[2025/6/22 19:05:11] 🔧 using tool weather
[2025/6/22 19:05:11] ✓ use tools success
⚙️ Agent Response 今天杭州的天气是小雨气温为24.7°C湿度为95%空气质量指数AQI为26空气质量良好。
```

View File

@ -0,0 +1,6 @@
# 人机交互
openmcp-sdk 支持强大的人机交互HIL工作流程允许在自动化流程的任何环节进行人工干预。这一功能在由大语言模型LLM驱动的应用中尤为实用因为这类模型的输出可能需要验证、修正或补充上下文信息。
// to be continued ...

Binary file not shown.

After

Width:  |  Height:  |  Size: 163 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

View File

@ -0,0 +1,28 @@
# 连接多个 MCP 服务器
openmcp-sdk 提供了两种方法,让您可以在一个 agent 上同时连接多个 mcp 服务器。
## 方法一mcpconfig.json (推荐)
在 openmcp 插件中,你可以通过下面的面板连接多个 mcp 服务器并进行测试
![](./images/openmcp-multi-server.png)
这个时候你再去根据 [极速部署](./fast-deploy.md) 中的指示导出后sdk 就会自动帮你连接这多个服务器了。
## 方法二addMcpServer
您也可以通过下面的代码,在 agent 中添加多个 mcp 服务器:
```typescript
agent.addMcpServer({
connectionType: 'STDIO',
commandString: 'uv run main.py',
cwd: '/path/to/workspace',
});
agent.addMcpServer({
connectionType: 'STREAMABLE_HTTP',
url: 'go run /path/to/main.go',
});
```

View File

@ -0,0 +1,25 @@
# 发送多轮对话
如果想要更加精细地控制对话的上下文,可以传递一个数组给 `ainvoke` 方法:
```typescript
import { AssistantMessage, UserMessage } from 'openmcp-sdk/service/sdk';
const messages = [
UserMessage('我今天刚刚吃过一份非常棒的鸡鸣汤包'),
AssistantMessage('好的,我记住了'),
UserMessage('请问我今天吃过了什么?')
]
const result = await agent.ainvoke({ messages });
console.log(result);
```
运行上面的代码,你会得到如下的回复:
```
根据之前的对话记录,你今天提到过吃了一份 **鸡鸣汤包**,并形容它“非常棒”! 😊
需要帮你推荐其他类似的美食,或者聊聊这道汤包的特别之处吗?
```

View File

@ -0,0 +1,24 @@
# 设置对话参数
你可以通过 ainvoke 的第二个参数 setting 来设置对话参数:
```typescript
const messages = [
UserMessage('我今天刚刚吃过一份非常棒的鸡鸣汤包'),
AssistantMessage('好的,我记住了'),
UserMessage('请问我今天吃过了什么?')
]
const result = await agent.ainvoke({
messages: messages,
settings: {
systemPrompt: '你是一个非常友善的助手',
temperature: 0.7,
// ...
}
});
console.log(result);
```
更多参数涉及到 MCP 相关的高级用法,会在后续文档中加以描述。

View File

@ -0,0 +1,57 @@
# 任务循环
openmcp-sdk 是以任务循环的机制构建 agent 并允许用户与之交互的。如果用户需要实时控制这个任务循环,可以通过 openmcp-sdk 提供的事件来注册对应的钩子函数来完成这件事。
以 [极速部署](./fast-deploy.md) 中的为例,通过下面的代码,你可以获取到控制任务循环的对象:
```typescript
import { OmAgent } from '../openmcp-sdk/service/sdk';
const agent = new OmAgent();
agent.loadMcpConfig('./mcpconfig.json');
const loop = await agent.getLoop();
```
:::warning
注册钩子和获取 loop 必须在 `agent.ainvoke` 之前完成!
:::
通过这个 `loop` 对象,我们可以注册如下的钩子:
- `registerOnChunk`:在模型返回 chunk 时触发
- `registerOnDone`:在任务完成时触发
- `registerOnError`:在任务出错时触发
- `registerOnEpoch`:在每个任务轮次开始时触发
- `registerOnToolCall`:在调用工具函数前触发
- `registerOnToolCalled`:在调用工具函数后触发
这些钩子函数接收一个回调函数,回调函数会在对应事件触发时被调用。
```typescript
loop.registerOnChunk((chunk) => {
console.log('⚙️ Agent Chunk', chunk);
});
loop.registerOnDone(() => {
console.log('⚙️ Agent Done');
});
loop.registerOnError((err) => {
console.log('⚙️ Agent Error', err);
});
loop.registerOnEpoch(() => {
console.log('⚙️ Agent Epoch');
});
loop.registerOnToolCall((toolCall) => {
console.log('⚙️ Agent Tool Call', toolCall);
return toolCall;
});
loop.registerOnToolCalled((toolCalled) => {
console.log('⚙️ Agent Tool Called', toolCalled);
return toolCalled;
});
```