test-client.ts•3 kB
import { spawn } from 'child_process';
import { readFileSync } from 'fs';
import { join } from 'path';
// 這是一個簡單的 MCP 客戶端範例,用來測試 Notion MCP 伺服器
class MCPClient {
private child: any;
private messageId = 1;
constructor() {
// 啟動 MCP 伺服器
this.child = spawn('npm', ['run', 'dev'], {
stdio: ['pipe', 'pipe', 'pipe'],
env: { ...process.env, NOTION_TOKEN: 'your-token-here' }
});
this.child.stderr.on('data', (data: Buffer) => {
console.log('Server:', data.toString());
});
this.child.on('error', (error: Error) => {
console.error('Server error:', error);
});
}
private sendMessage(message: any) {
const jsonMessage = JSON.stringify(message) + '\n';
this.child.stdin.write(jsonMessage);
}
private async waitForResponse(): Promise<any> {
return new Promise((resolve) => {
this.child.stdout.once('data', (data: Buffer) => {
try {
const response = JSON.parse(data.toString().trim());
resolve(response);
} catch (error) {
console.error('Failed to parse response:', error);
resolve(null);
}
});
});
}
async initialize() {
const initMessage = {
jsonrpc: '2.0',
id: this.messageId++,
method: 'initialize',
params: {
protocolVersion: '2024-11-05',
capabilities: {
roots: {
listChanged: true
}
},
clientInfo: {
name: 'notion-mcp-test-client',
version: '1.0.0'
}
}
};
this.sendMessage(initMessage);
const response = await this.waitForResponse();
console.log('Initialize response:', response);
return response;
}
async listTools() {
const message = {
jsonrpc: '2.0',
id: this.messageId++,
method: 'tools/list'
};
this.sendMessage(message);
const response = await this.waitForResponse();
console.log('Available tools:', response);
return response;
}
async searchPages(query: string) {
const message = {
jsonrpc: '2.0',
id: this.messageId++,
method: 'tools/call',
params: {
name: 'search-pages',
arguments: {
query
}
}
};
this.sendMessage(message);
const response = await this.waitForResponse();
console.log('Search results:', response);
return response;
}
close() {
this.child.kill();
}
}
// 使用範例
async function main() {
console.log('測試 Notion MCP 伺服器...');
const client = new MCPClient();
try {
// 初始化連接
await client.initialize();
// 列出可用工具
await client.listTools();
// 搜尋頁面(需要有效的 Notion token)
// await client.searchPages('meeting');
} catch (error) {
console.error('測試失敗:', error);
} finally {
client.close();
}
}
if (require.main === module) {
main();
}