Agent as an MCP Tool
easy5 minagent-as-mcp-server.ts
You want your whole agent — not just its tools — callable from an MCP client, with follow-up questions in the same thread.
What it shows
- Serve agents with
serveAgents() - Continue a conversation by passing the returned
threadId
The code
agent-as-mcp-server.ts
import { Agent, Cogitator, tool } from '@cogitator-ai/core';
import { MCPClient, serveAgents } from '@cogitator-ai/mcp';
import { z } from 'zod';
const apiKey = process.env.GOOGLE_API_KEY;
if (!apiKey) throw new Error('Set GOOGLE_API_KEY');
const rates: Record<string, number> = { EUR: 0.92, GBP: 0.79, JPY: 151.3 };
const convert = tool({
name: 'convert_currency',
description: 'Convert an amount of US dollars into another currency.',
parameters: z.object({
amount: z.number().describe('Amount in USD'),
to: z.enum(['EUR', 'GBP', 'JPY']).describe('Target currency'),
}),
execute: async ({ amount, to }) => ({ amount: Math.round(amount * rates[to] * 100) / 100, currency: to }),
});
const cog = new Cogitator({
llm: { providers: { google: { apiKey } } },
memory: { adapter: 'memory' },
});
const travel = new Agent({
name: 'travel_planner',
description: 'Plans trips and budgets, converting prices between currencies.',
model: 'google/gemini-3.5-flash-lite',
instructions: 'You plan trips. Use convert_currency for currency questions. Two sentences at most.',
tools: [convert],
temperature: 0.2,
});
const server = await serveAgents(cog, travel, { transport: 'http', host: '127.0.0.1', port: 0 });
const client = await MCPClient.connect({
transport: 'http',
url: `http://127.0.0.1:${server.getPort()}/mcp`,
});
try {
const first = (await client.callTool('travel_planner', {
task: 'My hotel in Lisbon costs $180 a night. How much is that in euros?',
})) as { output: string; threadId: string };
console.log(first.output);
const followUp = (await client.callTool('travel_planner', {
task: 'And for 4 nights?',
threadId: first.threadId,
})) as { output: string };
console.log(followUp.output);
} finally {
await client.close();
await server.stop();
await cog.close();
}Run it
install · bash
pnpm add @cogitator-ai/core @cogitator-ai/mcp zodEnvironment
GOOGLE_API_KEYrun · bash
GOOGLE_API_KEY=your-key npx tsx agent-as-mcp-server.tsOr run the full example from a clone of the repository (keys in .env):
repository · bash
npx tsx examples/mcp/04-agent-as-mcp-server.ts