forked from elizaOS/eliza
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
284 lines (245 loc) · 7.3 KB
/
Copy pathserver.ts
File metadata and controls
284 lines (245 loc) · 7.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
/**
* elizaOS MCP Agent Server - TypeScript
*
* Exposes an elizaOS agent as an MCP server. Any MCP-compatible client
* (Claude Desktop, VS Code, etc.) can interact with your agent.
*
* Uses real elizaOS runtime with OpenAI and SQL plugins.
*/
import {
AgentRuntime,
ChannelType,
createCharacter,
createMessageMemory,
stringToUuid,
type UUID,
} from "@elizaos/core";
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
type CallToolResult,
ListToolsRequestSchema,
type ListToolsResult,
type Tool,
} from "@modelcontextprotocol/sdk/types.js";
import { v4 as uuidv4 } from "uuid";
// ============================================================================
// Tool Argument Types
// ============================================================================
interface ChatToolArgs {
message: string;
userId?: string;
}
interface CallToolRequest {
params: {
name: string;
arguments?: Record<string, unknown>;
};
}
// ============================================================================
// Configuration
// ============================================================================
const CHARACTER = createCharacter({
name: "Eliza",
bio: "A helpful AI assistant powered by elizaOS, accessible via MCP.",
system:
"You are a helpful, friendly AI assistant. Be concise and informative.",
});
// ============================================================================
// MCP Tools Definition
// ============================================================================
const TOOLS: Tool[] = [
{
name: "chat",
description: "Send a message to the Eliza agent and receive a response",
inputSchema: {
type: "object" as const,
properties: {
message: {
type: "string",
description: "The message to send to the agent",
},
userId: {
type: "string",
description: "Optional user identifier for conversation context",
},
},
required: ["message"],
},
},
{
name: "get_agent_info",
description: "Get information about the Eliza agent",
inputSchema: {
type: "object" as const,
properties: {},
},
},
];
// ============================================================================
// Agent Runtime
// ============================================================================
let runtime: AgentRuntime | null = null;
const roomId = stringToUuid("mcp-room");
const worldId = stringToUuid("mcp-world");
async function initializeRuntime(): Promise<AgentRuntime> {
if (runtime) return runtime;
console.error("🚀 Initializing elizaOS runtime...");
const [{ default: sqlPlugin }, { openaiPlugin }] = await Promise.all([
import("@elizaos/plugin-sql"),
import("@elizaos/plugin-openai"),
]);
runtime = new AgentRuntime({
character: CHARACTER,
plugins: [sqlPlugin, openaiPlugin],
});
await runtime.initialize();
console.error("✅ elizaOS runtime initialized");
return runtime;
}
async function handleChat(message: string, userId?: string): Promise<string> {
const rt = await initializeRuntime();
const entityId = userId ? stringToUuid(userId) : (uuidv4() as UUID);
// Ensure connection
await rt.ensureConnection({
entityId,
roomId,
worldId,
userName: userId ?? "MCP User",
source: "mcp",
channelId: "mcp",
serverId: "mcp-server",
type: ChannelType.DM,
} as Parameters<typeof rt.ensureConnection>[0]);
// Create message memory
const messageMemory = createMessageMemory({
id: uuidv4() as UUID,
entityId,
roomId,
content: {
text: message,
source: "client_chat",
channelType: ChannelType.DM,
},
});
// Process message and collect response
let response = "";
await rt.messageService?.handleMessage(rt, messageMemory, async (content) => {
if (content?.text) {
response += content.text;
}
return [];
});
return response || "I didn't generate a response. Please try again.";
}
function getAgentInfo(): { name: string; bio: string; capabilities: string[] } {
const bio = CHARACTER.bio;
const bioStr = Array.isArray(bio)
? bio.join(" ")
: (bio ?? "An AI assistant");
return {
name: CHARACTER.name ?? "Eliza",
bio: bioStr,
capabilities: [
"Natural language conversation",
"Helpful responses",
"Context-aware dialogue",
],
};
}
// ============================================================================
// MCP Server
// ============================================================================
async function main(): Promise<void> {
const server = new Server(
{
name: "eliza-mcp-server",
version: "1.0.0",
},
{
capabilities: {
tools: {},
},
},
);
// Helper to handle Zod schema type compatibility
// Due to Zod version differences between MCP SDK and project dependencies
type RequestSchema = Parameters<typeof server.setRequestHandler>[0];
// Handle tool listing
server.setRequestHandler(
ListToolsRequestSchema as RequestSchema,
async (): Promise<ListToolsResult> => ({
tools: TOOLS,
}),
);
// Handle tool calls
server.setRequestHandler(
CallToolRequestSchema as RequestSchema,
async (request: CallToolRequest): Promise<CallToolResult> => {
const { name, arguments: args } = request.params;
try {
switch (name) {
case "chat": {
const chatArgs = args as ChatToolArgs | undefined;
const message = chatArgs?.message;
const userId = chatArgs?.userId;
if (!message || typeof message !== "string") {
return {
content: [{ type: "text", text: "Error: message is required" }],
isError: true,
};
}
const response = await handleChat(message, userId);
return {
content: [{ type: "text", text: response }],
};
}
case "get_agent_info": {
const info = getAgentInfo();
return {
content: [{ type: "text", text: JSON.stringify(info, null, 2) }],
};
}
default:
return {
content: [{ type: "text", text: `Unknown tool: ${name}` }],
isError: true,
};
}
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : String(error);
return {
content: [{ type: "text", text: `Error: ${errorMessage}` }],
isError: true,
};
}
},
);
// Start server with stdio transport
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("🌐 elizaOS MCP Server running on stdio");
console.error("📚 Available tools: chat, get_agent_info");
}
async function shutdown(): Promise<void> {
if (runtime) {
await runtime.stop();
runtime = null;
}
}
// Handle graceful shutdown
process.on("SIGINT", async () => {
console.error("\n👋 Shutting down...");
await shutdown();
process.exit(0);
});
process.on("SIGTERM", async () => {
await shutdown();
process.exit(0);
});
main().catch((error) => {
console.error("Fatal error:", error);
process.exit(1);
});