Use an MCP Server

medium10 minmcp-client.ts

There is already an MCP server for what you need — here the filesystem one. Your agent should use its tools.

What it shows

  • Connect over stdio with MCPClient.connect()
  • Call tools directly, or convert them with getTools() and give them to an agent

The code

mcp-client.ts
import { Agent, Cogitator } from '@cogitator-ai/core';
import { MCPClient } from '@cogitator-ai/mcp';
import { mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';

const apiKey = process.env.GOOGLE_API_KEY;
if (!apiKey) throw new Error('Set GOOGLE_API_KEY');

const allowedDir = join(process.cwd(), 'mcp-files');
mkdirSync(allowedDir, { recursive: true });
writeFileSync(
  join(allowedDir, 'inventory.json'),
  JSON.stringify({ items: [{ name: 'Hoverboard', qty: 12, price: 499.99 }, { name: 'Flux Capacitor', qty: 3, price: 1955 }] })
);

const client = await MCPClient.connect({
  transport: 'stdio',
  command: 'npx',
  args: ['-y', '@modelcontextprotocol/server-filesystem', allowedDir],
  timeout: 30_000,
});

try {
  for (const definition of await client.listToolDefinitions()) {
    console.log(`${definition.name}: ${definition.description}`);
  }

  console.log(await client.callTool('list_directory', { path: allowedDir }));

  const tools = (await client.getTools()).filter((t) =>
    ['read_text_file', 'read_file', 'list_directory'].includes(t.name)
  );

  const cog = new Cogitator({ llm: { providers: { google: { apiKey } } } });
  const agent = new Agent({
    name: 'fs-assistant',
    model: 'google/gemini-3.5-flash-lite',
    instructions: `You can read and list files in ${allowedDir}. Be concise.`,
    tools,
    temperature: 0.2,
    maxIterations: 10,
  });

  const result = await cog.run(agent, {
    input: `Read inventory.json in ${allowedDir} and tell me the total stock value (qty * price).`,
  });
  console.log(result.output);
  await cog.close();
} finally {
  await client.close();
}

Run it

install · bash
pnpm add @cogitator-ai/core @cogitator-ai/mcp
EnvironmentGOOGLE_API_KEY
run · bash
GOOGLE_API_KEY=your-key npx tsx mcp-client.ts

Or run the full example from a clone of the repository (keys in .env):

repository · bash
npx tsx examples/mcp/01-mcp-client.ts

Learn more