refactor(mcp): extract MCP core into shared chatlab-mcp package

Move MCP Server logic (tool registration, resource registration, schema
conversion) from apps/cli/src/mcp.ts to packages/mcp-server so both CLI
and Desktop can share the same MCP implementation.

- New package: chatlab-mcp (packages/mcp-server) with McpDatabaseManager
  interface abstraction
- CLI mcp.ts slimmed to thin entry (~37 lines) calling startMcpServer()
- Desktop helper prototype at apps/desktop/helper/mcp.ts for dev-time
  MCP without GUI
- All 8 MCP tools and 3 resources unchanged

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
diguaandCursor authored and digua committed 2026-05-22 10:20:39 +08:00
1 parent e3370b52c2
commit d022bed48f
17 files changed
+377 -198

No files matched your search

+42
View File
@@ -0,0 +1,42 @@
{
"name": "chatlab-mcp",
"version": "0.1.0",
"description": "ChatLab MCP Server — shared core for CLI and Desktop",
"main": "./dist/index.mjs",
"files": [
"dist/"
],
"engines": {
"node": ">=20"
},
"publishConfig": {
"access": "public"
},
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/ChatLab/ChatLab.git",
"directory": "packages/mcp-server"
},
"homepage": "https://github.com/ChatLab/ChatLab",
"keywords": [
"chatlab",
"mcp",
"model-context-protocol",
"chat",
"analysis"
],
"scripts": {
"build": "tsup",
"dev": "tsup --watch"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.12.1",
"zod": "^3.24.4"
},
"devDependencies": {
"@openchatlab/core": "workspace:*",
"@openchatlab/tools": "workspace:*",
"tsup": "^8.5.0"
}
}
+9
View File
@@ -0,0 +1,9 @@
/**
* chatlab-mcp
*
* Shared MCP Server core for CLI and Desktop helper.
* Registers ChatLab tools and resources over stdio transport.
*/
export { startMcpServer } from './server'
export type { McpServerOptions, McpDatabaseManager } from './types'
+46
View File
@@ -0,0 +1,46 @@
/**
* JSON Schema → Zod conversion for MCP tool registration
*/
import { z } from 'zod'
/**
* Convert simple JSON Schema properties to a Zod shape object.
* Supports string / number / boolean / enum types.
*/
export function jsonSchemaToZod(
properties: Record<string, { type: string; description?: string; default?: unknown; enum?: unknown[] }>,
required?: string[]
): Record<string, z.ZodTypeAny> {
const shape: Record<string, z.ZodTypeAny> = {}
const requiredSet = new Set(required ?? [])
for (const [key, prop] of Object.entries(properties)) {
let zodType: z.ZodTypeAny
switch (prop.type) {
case 'number':
zodType = z.number().describe(prop.description ?? '')
break
case 'boolean':
zodType = z.boolean().describe(prop.description ?? '')
break
case 'string':
default:
if (prop.enum) {
zodType = z.enum(prop.enum as [string, ...string[]]).describe(prop.description ?? '')
} else {
zodType = z.string().describe(prop.description ?? '')
}
break
}
if (!requiredSet.has(key)) {
zodType = zodType.optional()
}
shape[key] = zodType
}
return shape
}
+150
View File
@@ -0,0 +1,150 @@
/**
* ChatLab MCP Server core
*
* Registers @openchatlab/tools as MCP tools and exposes session data as MCP resources.
* Communicates with AI agents (Claude Desktop, Cursor, etc.) via stdio transport.
*/
import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js'
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
import { z } from 'zod'
import { getSessionMeta, getSessionOverview, getDatabaseSchema } from '@openchatlab/core'
import { MCP_TOOL_REGISTRY, CoreDataProvider } from '@openchatlab/tools'
import type { SessionListContext } from '@openchatlab/tools/src/definitions/sessions'
import type { McpDatabaseManager, McpServerOptions } from './types'
import { jsonSchemaToZod } from './schema'
const MCP_TOOL_PREFIX = 'chatlab_'
function registerTools(server: McpServer, dbManager: McpDatabaseManager): void {
for (const tool of MCP_TOOL_REGISTRY) {
const mcpName = `${MCP_TOOL_PREFIX}${tool.name}`
if (tool.name === 'list_sessions') {
const zodShape = jsonSchemaToZod(tool.inputSchema.properties, tool.inputSchema.required)
server.tool(mcpName, tool.description, zodShape, async (params) => {
const context: SessionListContext = {
db: null as any,
sessionId: '',
listSessionIds: () => dbManager.listSessionIds(),
openDb: (id) => dbManager.open(id),
}
const result = await tool.handler(params as Record<string, unknown>, context)
return { content: [{ type: 'text' as const, text: result.content }] }
})
continue
}
const sessionsToolMcpName = `${MCP_TOOL_PREFIX}list_sessions`
const zodShape = {
session_id: z.string().describe(`Session ID (use ${sessionsToolMcpName} to get available sessions)`),
...jsonSchemaToZod(tool.inputSchema.properties, tool.inputSchema.required),
}
server.tool(mcpName, tool.description, zodShape, async (params) => {
const sessionId = params.session_id as string
const db = dbManager.open(sessionId)
if (!db) {
return {
content: [{ type: 'text' as const, text: JSON.stringify({ error: `Session ${sessionId} not found` }) }],
isError: true,
}
}
const toolParams = { ...params } as Record<string, unknown>
delete toolParams.session_id
const result = await tool.handler(toolParams, { db, sessionId, dataProvider: new CoreDataProvider(db) })
return { content: [{ type: 'text' as const, text: result.content }] }
})
}
}
function registerResources(server: McpServer, dbManager: McpDatabaseManager): void {
server.resource('sessions-list', 'chatlab://sessions', { description: '所有已导入的聊天会话列表' }, async () => {
const sessionIds = dbManager.listSessionIds()
const sessions = sessionIds
.map((id) => {
const db = dbManager.open(id)
if (!db) return null
const meta = getSessionMeta(db)
if (!meta) return null
return { id, name: meta.name, platform: meta.platform, type: meta.type }
})
.filter(Boolean)
return {
contents: [
{
uri: 'chatlab://sessions',
text: JSON.stringify(sessions, null, 2),
mimeType: 'application/json',
},
],
}
})
server.resource(
'session-meta',
new ResourceTemplate('chatlab://sessions/{sessionId}/meta', { list: undefined }),
{ description: '会话元信息(名称、平台、消息数等)' },
async (uri, params) => {
const sessionId = params.sessionId as string
const db = dbManager.open(sessionId)
if (!db) {
return { contents: [{ uri: uri.href, text: '{"error": "Session not found"}', mimeType: 'application/json' }] }
}
const meta = getSessionMeta(db)
const overview = getSessionOverview(db)
return {
contents: [
{
uri: uri.href,
text: JSON.stringify({ ...meta, ...overview }, null, 2),
mimeType: 'application/json',
},
],
}
}
)
server.resource(
'session-schema',
new ResourceTemplate('chatlab://sessions/{sessionId}/schema', { list: undefined }),
{ description: '会话数据库的表结构' },
async (uri, params) => {
const sessionId = params.sessionId as string
const db = dbManager.open(sessionId)
if (!db) {
return { contents: [{ uri: uri.href, text: '{"error": "Session not found"}', mimeType: 'application/json' }] }
}
const schema = getDatabaseSchema(db)
return {
contents: [
{
uri: uri.href,
text: JSON.stringify(schema, null, 2),
mimeType: 'application/json',
},
],
}
}
)
}
export async function startMcpServer(options: McpServerOptions): Promise<void> {
const { version, name = 'chatlab', dbManager } = options
const server = new McpServer({ name, version })
registerTools(server, dbManager)
registerResources(server, dbManager)
const transport = new StdioServerTransport()
await server.connect(transport)
}
+21
View File
@@ -0,0 +1,21 @@
/**
* MCP Server public types
*/
import type { DatabaseAdapter } from '@openchatlab/core'
/**
* Minimal database manager interface for MCP Server.
* Both CLI's DatabaseManager and Desktop's helper can satisfy this contract.
*/
export interface McpDatabaseManager {
listSessionIds(): string[]
open(sessionId: string): DatabaseAdapter | null
}
export interface McpServerOptions {
version: string
/** MCP server name exposed to clients (default: 'chatlab') */
name?: string
dbManager: McpDatabaseManager
}
+14
View File
@@ -0,0 +1,14 @@
{
"extends": "../../tsconfig.node.json",
"compilerOptions": {
"composite": true,
"rootDir": "./src",
"outDir": "./dist"
},
"include": [
"src/**/*.ts",
"../../packages/shared-types/**/*",
"../../packages/core/**/*",
"../../packages/tools/**/*"
]
}
+17
View File
@@ -0,0 +1,17 @@
import { defineConfig } from 'tsup'
export default defineConfig({
entry: {
index: 'src/index.ts',
},
format: ['esm'],
dts: false,
outDir: 'dist',
outExtension: () => ({ js: '.mjs' }),
splitting: false,
sourcemap: true,
clean: true,
target: 'node20',
platform: 'node',
noExternal: [/^@openchatlab\//],
})