@n0ts123/mcplink-core 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,424 @@
1
+ # @mcplink/core
2
+
3
+ MCPLink 核心 SDK - AI Agent 工具调用框架
4
+
5
+ ## 安装
6
+
7
+ ```bash
8
+ npm install @mcplink/core ai @ai-sdk/openai
9
+ ```
10
+
11
+ 根据你使用的模型,还需要安装对应的 AI SDK:
12
+
13
+ ```bash
14
+ # OpenAI (GPT-4, GPT-3.5)
15
+ npm install @ai-sdk/openai
16
+
17
+ # Google (Gemini)
18
+ npm install @ai-sdk/google
19
+
20
+ # Anthropic (Claude)
21
+ npm install @ai-sdk/anthropic
22
+
23
+ # 兼容 OpenAI 格式的模型 (DeepSeek, Qwen, 等)
24
+ # 使用 @ai-sdk/openai 即可
25
+ ```
26
+
27
+ ## 快速开始
28
+
29
+ ### 最小示例
30
+
31
+ ```typescript
32
+ import { MCPLink } from '@mcplink/core'
33
+ import { createOpenAI } from '@ai-sdk/openai'
34
+
35
+ // 创建模型
36
+ const openai = createOpenAI({ apiKey: process.env.OPENAI_API_KEY })
37
+
38
+ // 创建 Agent
39
+ const agent = new MCPLink({
40
+ model: openai('gpt-4o'),
41
+ mcpServers: {
42
+ myTools: {
43
+ type: 'stdio',
44
+ command: 'node',
45
+ args: ['./my-mcp-server.js'],
46
+ },
47
+ },
48
+ })
49
+
50
+ // 初始化并对话
51
+ await agent.initialize()
52
+ const result = await agent.chat('你好')
53
+ console.log(result.content)
54
+ await agent.close()
55
+ ```
56
+
57
+ ### 流式响应
58
+
59
+ ```typescript
60
+ import { MCPLink, MCPLinkEventType } from '@mcplink/core'
61
+
62
+ const agent = new MCPLink({
63
+ model: openai('gpt-4o'),
64
+ systemPrompt: '你是一个智能助手',
65
+ maxIterations: 10,
66
+ mcpServers: { /* ... */ },
67
+ })
68
+
69
+ await agent.initialize()
70
+
71
+ // 流式处理
72
+ for await (const event of agent.chatStream('帮我查询订单')) {
73
+ switch (event.type) {
74
+ case MCPLinkEventType.THINKING_START:
75
+ console.log('💭 思考中...')
76
+ break
77
+
78
+ case MCPLinkEventType.THINKING_DELTA:
79
+ process.stdout.write(event.data.content || '')
80
+ break
81
+
82
+ case MCPLinkEventType.THINKING_END:
83
+ console.log('\n')
84
+ break
85
+
86
+ case MCPLinkEventType.TOOL_CALL_START:
87
+ console.log(`🔧 调用工具: ${event.data.toolName}`)
88
+ console.log(` 参数: ${JSON.stringify(event.data.toolArgs)}`)
89
+ break
90
+
91
+ case MCPLinkEventType.TOOL_RESULT:
92
+ const status = event.data.isError ? '❌' : '✅'
93
+ console.log(`${status} 结果 (${event.data.duration}ms)`)
94
+ break
95
+
96
+ case MCPLinkEventType.TEXT_START:
97
+ console.log('📝 回复:')
98
+ break
99
+
100
+ case MCPLinkEventType.TEXT_DELTA:
101
+ process.stdout.write(event.data.content || '')
102
+ break
103
+
104
+ case MCPLinkEventType.TEXT_END:
105
+ console.log('\n')
106
+ break
107
+
108
+ case MCPLinkEventType.COMPLETE:
109
+ console.log(`✅ 完成! 总耗时: ${event.data.totalDuration}ms`)
110
+ break
111
+
112
+ case MCPLinkEventType.ERROR:
113
+ console.error(`❌ 错误: ${event.data.error}`)
114
+ break
115
+ }
116
+ }
117
+ ```
118
+
119
+ ## 配置选项
120
+
121
+ ### MCPLinkConfig
122
+
123
+ ```typescript
124
+ interface MCPLinkConfig {
125
+ /**
126
+ * AI 模型实例(必填)
127
+ * 使用 Vercel AI SDK 创建的模型
128
+ */
129
+ model: LanguageModel
130
+
131
+ /**
132
+ * 模型名称
133
+ * 用于自动检测是否支持原生 function calling
134
+ * 如果不提供,会尝试从 model.modelId 获取
135
+ */
136
+ modelName?: string
137
+
138
+ /**
139
+ * 系统提示词
140
+ * 定义 AI 的角色和行为
141
+ */
142
+ systemPrompt?: string
143
+
144
+ /**
145
+ * 最大迭代次数
146
+ * 防止无限循环,默认 10
147
+ */
148
+ maxIterations?: number
149
+
150
+ /**
151
+ * MCP 服务器配置
152
+ * key 是服务器 ID,value 是服务器配置
153
+ */
154
+ mcpServers?: Record<string, MCPServerConfig>
155
+
156
+ /**
157
+ * 是否强制使用 Prompt-Based 模式
158
+ * - true: 强制使用 PromptBasedAgent
159
+ * - false: 强制使用原生 Agent
160
+ * - 'auto' | undefined: 自动检测
161
+ */
162
+ usePromptBasedTools?: boolean | 'auto'
163
+ }
164
+ ```
165
+
166
+ ### MCP 服务器配置
167
+
168
+ ```typescript
169
+ // Stdio 模式(本地进程)
170
+ interface MCPServerConfigStdio {
171
+ type: 'stdio'
172
+ command: string // 启动命令
173
+ args?: string[] // 命令参数
174
+ env?: Record<string, string> // 环境变量
175
+ }
176
+
177
+ // SSE 模式(远程服务)
178
+ interface MCPServerConfigSSE {
179
+ type: 'sse'
180
+ url: string // SSE 端点 URL
181
+ headers?: Record<string, string> // 请求头
182
+ }
183
+ ```
184
+
185
+ ## 多模型支持
186
+
187
+ ### OpenAI
188
+
189
+ ```typescript
190
+ import { createOpenAI } from '@ai-sdk/openai'
191
+
192
+ const openai = createOpenAI({
193
+ apiKey: process.env.OPENAI_API_KEY,
194
+ })
195
+
196
+ const agent = new MCPLink({
197
+ model: openai('gpt-4o'), // 或 gpt-4o-mini, gpt-3.5-turbo
198
+ })
199
+ ```
200
+
201
+ ### Google Gemini
202
+
203
+ ```typescript
204
+ import { createGoogleGenerativeAI } from '@ai-sdk/google'
205
+
206
+ const google = createGoogleGenerativeAI({
207
+ apiKey: process.env.GOOGLE_API_KEY,
208
+ })
209
+
210
+ const agent = new MCPLink({
211
+ model: google('gemini-1.5-flash'), // 或 gemini-1.5-pro
212
+ })
213
+ ```
214
+
215
+ ### Anthropic Claude
216
+
217
+ ```typescript
218
+ import { createAnthropic } from '@ai-sdk/anthropic'
219
+
220
+ const anthropic = createAnthropic({
221
+ apiKey: process.env.ANTHROPIC_API_KEY,
222
+ })
223
+
224
+ const agent = new MCPLink({
225
+ model: anthropic('claude-3-5-sonnet-20241022'),
226
+ })
227
+ ```
228
+
229
+ ### 兼容 OpenAI 的模型
230
+
231
+ DeepSeek、Qwen、GLM 等兼容 OpenAI 格式的模型:
232
+
233
+ ```typescript
234
+ import { createOpenAI } from '@ai-sdk/openai'
235
+
236
+ // DeepSeek
237
+ const deepseek = createOpenAI({
238
+ apiKey: process.env.DEEPSEEK_API_KEY,
239
+ baseURL: 'https://api.deepseek.com/v1',
240
+ })
241
+
242
+ const agent = new MCPLink({
243
+ model: deepseek('deepseek-chat'),
244
+ })
245
+
246
+ // 通义千问
247
+ const qwen = createOpenAI({
248
+ apiKey: process.env.QWEN_API_KEY,
249
+ baseURL: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
250
+ })
251
+
252
+ const agent = new MCPLink({
253
+ model: qwen('qwen-turbo'),
254
+ })
255
+ ```
256
+
257
+ ## 多轮对话
258
+
259
+ ```typescript
260
+ // 方式一:手动管理历史
261
+ const history: Array<{ role: 'user' | 'assistant'; content: string }> = []
262
+
263
+ // 第一轮
264
+ let response = ''
265
+ for await (const event of agent.chatStream('帮我查订单')) {
266
+ if (event.type === MCPLinkEventType.TEXT_DELTA) {
267
+ response += event.data.content || ''
268
+ }
269
+ }
270
+ history.push({ role: 'user', content: '帮我查订单' })
271
+ history.push({ role: 'assistant', content: response })
272
+
273
+ // 第二轮(携带历史)
274
+ for await (const event of agent.chatStream('第一个订单的详情', { history })) {
275
+ // ...
276
+ }
277
+ ```
278
+
279
+ ## 工具过滤
280
+
281
+ ```typescript
282
+ // 只允许使用特定工具
283
+ for await (const event of agent.chatStream('搜索产品', {
284
+ allowedTools: ['search_products', 'get_product_details'],
285
+ })) {
286
+ // 只会调用 search_products 和 get_product_details
287
+ }
288
+ ```
289
+
290
+ ## 手动工具管理
291
+
292
+ ```typescript
293
+ // 获取所有可用工具
294
+ const tools = agent.getTools()
295
+ console.log(tools.map(t => t.name))
296
+
297
+ // 手动调用工具
298
+ const result = await agent.callTool('search_products', {
299
+ keyword: 'APC6-01',
300
+ })
301
+
302
+ // 获取 MCP 服务器状态
303
+ const statuses = agent.getMCPServerStatuses()
304
+ console.log(statuses)
305
+
306
+ // 手动控制 MCP 服务器
307
+ await agent.startMCPServer('myServer')
308
+ await agent.stopMCPServer('myServer')
309
+ ```
310
+
311
+ ## 事件类型详解
312
+
313
+ | 事件 | 说明 | 数据 |
314
+ |------|------|------|
315
+ | `iteration_start` | 迭代开始 | `{ iteration, maxIterations }` |
316
+ | `iteration_end` | 迭代结束 | `{ iteration }` |
317
+ | `thinking_start` | 思考开始 | `{}` |
318
+ | `thinking_delta` | 思考内容 | `{ content }` |
319
+ | `thinking_end` | 思考结束 | `{}` |
320
+ | `text_start` | 文本开始 | `{}` |
321
+ | `text_delta` | 文本内容 | `{ content }` |
322
+ | `text_end` | 文本结束 | `{}` |
323
+ | `tool_call_start` | 工具调用开始 | `{ toolName, toolCallId, toolArgs }` |
324
+ | `tool_executing` | 工具执行中 | `{ toolName, toolCallId, toolArgs }` |
325
+ | `tool_result` | 工具执行结果 | `{ toolName, toolResult, toolCallId, duration, isError }` |
326
+ | `complete` | 任务完成 | `{ totalDuration, totalIterations }` |
327
+ | `error` | 发生错误 | `{ error }` |
328
+
329
+ ## 高级用法
330
+
331
+ ### 直接使用 Agent
332
+
333
+ 如果你只需要使用特定的 Agent 实现:
334
+
335
+ ```typescript
336
+ import { Agent, PromptBasedAgent, MCPManager } from '@mcplink/core'
337
+ import { createOpenAI } from '@ai-sdk/openai'
338
+
339
+ const openai = createOpenAI({ apiKey: '...' })
340
+ const mcpManager = new MCPManager()
341
+
342
+ // 添加 MCP 服务器
343
+ mcpManager.addServer('myTools', {
344
+ type: 'stdio',
345
+ command: 'node',
346
+ args: ['./server.js'],
347
+ })
348
+
349
+ // 启动服务器
350
+ await mcpManager.startAll()
351
+
352
+ // 使用原生 Agent(适用于支持 function calling 的模型)
353
+ const nativeAgent = new Agent(openai('gpt-4o'), mcpManager, {
354
+ systemPrompt: '你是一个智能助手',
355
+ maxIterations: 10,
356
+ })
357
+
358
+ // 使用 Prompt-Based Agent(适用于所有模型)
359
+ const promptAgent = new PromptBasedAgent(openai('gpt-4o'), mcpManager, {
360
+ systemPrompt: '你是一个智能助手',
361
+ maxIterations: 10,
362
+ })
363
+
364
+ // 流式对话
365
+ for await (const event of promptAgent.chatStream('你好')) {
366
+ console.log(event)
367
+ }
368
+
369
+ // 关闭
370
+ await mcpManager.stopAll()
371
+ ```
372
+
373
+ ### 自定义 MCP 管理器
374
+
375
+ ```typescript
376
+ import { MCPManager } from '@mcplink/core'
377
+
378
+ const mcpManager = new MCPManager()
379
+
380
+ // 添加多个服务器
381
+ mcpManager.addServer('business', {
382
+ type: 'stdio',
383
+ command: 'node',
384
+ args: ['./business-server.js'],
385
+ })
386
+
387
+ mcpManager.addServer('database', {
388
+ type: 'sse',
389
+ url: 'http://localhost:8080/mcp',
390
+ headers: { Authorization: 'Bearer xxx' },
391
+ })
392
+
393
+ // 按需启动
394
+ await mcpManager.startServer('business')
395
+
396
+ // 获取所有工具
397
+ const tools = mcpManager.getAllTools()
398
+
399
+ // 调用工具
400
+ const result = await mcpManager.callTool('search_products', { keyword: 'test' })
401
+
402
+ // 获取状态
403
+ const statuses = mcpManager.getServerStatuses()
404
+ ```
405
+
406
+ ## TypeScript 类型
407
+
408
+ ```typescript
409
+ import type {
410
+ MCPLinkConfig,
411
+ MCPServerConfig,
412
+ MCPLinkEvent,
413
+ MCPTool,
414
+ MCPServerStatus,
415
+ ChatResult,
416
+ } from '@mcplink/core'
417
+
418
+ import { MCPLinkEventType } from '@mcplink/core'
419
+ ```
420
+
421
+ ## 许可证
422
+
423
+ MIT
424
+