mcp-agent-kit

We need to translate the given text from English to Brazilian Portuguese. The text describes an SDK for building MCP servers, agents, and LLM integrations. We must preserve product names, protocol names, URLs, numbers, technical terms. The name "mcp-agent-kit" is not in the text, so we don't include it. We translate only the text inside <text>. No extra commentary, labels, etc. Let's translate: "a complete and intuitive SDK for building MCP Servers, MCP Agents, and LLM integrations (OpenAI, Claude, Gemini) with minimal effort. It abstracts all the complexity of the MCP protocol, provides an intelligent agent with automatic model routing, and includes a universal client for external APIs all through a single, simple, and powerful interface. Perfect for chatbots, enterprise automation, internal system integrations, and rapid development of MCP-based ecosystems." Translation to Portuguese (BR): "um SDK completo e intuitivo para construir Servidores MCP, Agentes MCP e integrações com LLMs (OpenAI, Claude, Gemini

Documentação

mcp-agent-kit

A maneira mais fácil de criar servidores MCP, agentes de IA e chatbots com qualquer LLM

npm version License: MIT TypeScript

mcp-agent-kit é um pacote TypeScript que simplifica a criação de:

  • 🔌 Servidores MCP (Model Context Protocol)
  • 🤖 Agentes de IA com múltiplos provedores de LLM
  • 🧠 Roteadores Inteligentes para orquestração multi-LLM
  • 💬 Chatbots com memória de conversa
  • 🌐 Auxiliares de API com retry e timeout

Recursos

  • Zero Config: Funciona imediatamente com padrões inteligentes
  • Multi-Provedor: Suporte a OpenAI, Anthropic, Gemini, Ollama
  • Type-Safe: Suporte completo a TypeScript com autocomplete
  • Pronto para Produção: Retry, timeout e tratamento de erros integrados
  • Amigável para Desenvolvedores: Configuração em uma linha para recursos complexos
  • Extensível: Fácil adicionar provedores personalizados e middleware

Instalação

npm install mcp-agent-kit

Início Rápido

Crie um Agente de IA (1 linha!)

import { createAgent } from "mcp-agent-kit";

const agent = createAgent({ provider: "openai" });
const response = await agent.chat("Hello!");
console.log(response.content);

Crie um Servidor MCP (1 função!)

import { createMCPServer } from "mcp-agent-kit";

const server = createMCPServer({
  name: "my-server",
  tools: [
    {
      name: "get_weather",
      description: "Get weather for a location",
      inputSchema: {
        type: "object",
        properties: {
          location: { type: "string" },
        },
      },
      handler: async ({ location }) => {
        return `Weather in ${location}: Sunny, 72°F`;
      },
    },
  ],
});

await server.start();

Crie um Chatbot com Memória

import { createChatbot, createAgent } from "mcp-agent-kit";

const bot = createChatbot({
  agent: createAgent({ provider: "openai" }),
  system: "You are a helpful assistant",
  maxHistory: 10,
});

await bot.chat("Hi, my name is John");
await bot.chat("What is my name?"); // Remembers context!

Documentação

Sumário


Agentes de IA

Crie agentes inteligentes que funcionam com múltiplos provedores de LLM.

Uso Básico

import { createAgent } from "mcp-agent-kit";

const agent = createAgent({
  provider: "openai",
  model: "gpt-4-turbo-preview",
  temperature: 0.7,
  maxTokens: 2000,
});

const response = await agent.chat("Explain TypeScript");
console.log(response.content);

Provedores Suportados

ProvedorModelosChave de API Necessária
OpenAIGPT-4, GPT-3.5✅ Sim
AnthropicClaude 3.5, Claude 3✅ Sim
GeminiGemini 2.0+✅ Sim
OllamaModelos locais❌ Não

Com Ferramentas (Chamada de Função)

const agent = createAgent({
  provider: "openai",
  tools: [
    {
      name: "calculate",
      description: "Perform calculations",
      parameters: {
        type: "object",
        properties: {
          operation: { type: "string", enum: ["add", "subtract"] },
          a: { type: "number" },
          b: { type: "number" },
        },
        required: ["operation", "a", "b"],
      },
      handler: async ({ operation, a, b }) => {
        return operation === "add" ? a + b : a - b;
      },
    },
  ],
});

const response = await agent.chat("What is 15 + 27?");

Com Prompt de Sistema

const agent = createAgent({
  provider: "anthropic",
  system: "You are an expert Python developer. Always provide code examples.",
});

Chamada Inteligente de Ferramentas

A Chamada Inteligente de Ferramentas adiciona confiabilidade e desempenho à execução de ferramentas com retry automático, timeout e cache.

Configuração Básica

const agent = createAgent({
  provider: "openai",
  toolConfig: {
    forceToolUse: true,      // Force model to use tools
    maxRetries: 3,           // Retry up to 3 times on failure
    toolTimeout: 30000,      // 30 second timeout
    onToolNotCalled: "retry", // Action when tool not called
  },
  tools: [...],
});

Com Cache

const agent = createAgent({
  provider: "openai",
  toolConfig: {
    cacheResults: {
      enabled: true,
      ttl: 300000,    // Cache for 5 minutes
      maxSize: 100,   // Store up to 100 results
    },
  },
  tools: [...],
});

Execução Direta de Ferramentas

// Execute a tool directly with retry and caching
const result = await agent.executeTool("get_weather", {
  location: "San Francisco, CA",
});

Opções de Configuração

OpçãoTipoPadrãoDescrição
forceToolUsebooleanfalseForça o modelo a usar ferramentas quando disponíveis
maxRetriesnumber3Número máximo de tentativas de retry em falha de ferramenta
onToolNotCalledstring"retry"Ação quando a ferramenta não é chamada: "retry", "error", "warn", "allow"
toolTimeoutnumber30000Timeout para execução da ferramenta (ms)
cacheResults.enabledbooleantrueHabilita cache de resultados
cacheResults.ttlnumber300000Tempo de vida do cache (ms)
cacheResults.maxSizenumber100Máximo de resultados em cache
debugbooleanfalseHabilita log de depuração

Exemplo Completo

const agent = createAgent({
  provider: "openai",
  model: "gpt-4-turbo-preview",
  toolConfig: {
    forceToolUse: true,
    maxRetries: 3,
    onToolNotCalled: "retry",
    toolTimeout: 30000,
    cacheResults: {
      enabled: true,
      ttl: 300000,
      maxSize: 100,
    },
    debug: true,
  },
  tools: [
    {
      name: "get_weather",
      description: "Get current weather for a location",
      parameters: {
        type: "object",
        properties: {
          location: { type: "string" },
        },
        required: ["location"],
      },
      handler: async ({ location }) => {
        // Your weather API logic
        return { location, temp: 72, condition: "Sunny" };
      },
    },
  ],
});

// Use in chat - tools are automatically called
const response = await agent.chat("What's the weather in NYC?");

// Or execute directly with retry and caching
const result = await agent.executeTool("get_weather", {
  location: "New York, NY",
});

Servidores MCP

Crie servidores Model Context Protocol para expor ferramentas e recursos.

Servidor MCP Básico

import { createMCPServer } from "mcp-agent-kit";

const server = createMCPServer({
  name: "my-mcp-server",
  port: 7777,
  logLevel: "info",
});

await server.start(); // Starts on stdio by default

Com Ferramentas

const server = createMCPServer({
  name: "weather-server",
  tools: [
    {
      name: "get_weather",
      description: "Get current weather",
      inputSchema: {
        type: "object",
        properties: {
          location: { type: "string" },
          units: { type: "string", enum: ["celsius", "fahrenheit"] },
        },
        required: ["location"],
      },
      handler: async ({ location, units = "celsius" }) => {
        // Your weather API logic here
        return { location, temp: 22, units, condition: "Sunny" };
      },
    },
  ],
});

Com Recursos

const server = createMCPServer({
  name: "data-server",
  resources: [
    {
      uri: "config://app-settings",
      name: "Application Settings",
      description: "Current app configuration",
      mimeType: "application/json",
      handler: async () => {
        return JSON.stringify({ version: "1.0.0", env: "production" });
      },
    },
  ],
});

Transporte WebSocket

const server = createMCPServer({
  name: "ws-server",
  port: 8080,
});

await server.start("websocket"); // Use WebSocket instead of stdio

Roteador LLM

Roteie requisições para diferentes LLMs com base em regras inteligentes.

Roteador Básico

import { createLLMRouter } from "mcp-agent-kit";

const router = createLLMRouter({
  rules: [
    {
      when: (input) => input.length < 200,
      use: { provider: "openai", model: "gpt-4-turbo-preview" },
    },
    {
      when: (input) => input.includes("code"),
      use: { provider: "anthropic", model: "claude-3-5-sonnet-20241022" },
    },
    {
      default: true,
      use: { provider: "openai", model: "gpt-4-turbo-preview" },
    },
  ],
});

const response = await router.route("Write a function to sort an array");

Com Fallback e Retry

const router = createLLMRouter({
  rules: [...],
  fallback: {
    provider: 'openai',
    model: 'gpt-4-turbo-preview'
  },
  retryAttempts: 3,
  logLevel: 'debug'
});

Estatísticas do Roteador

const stats = router.getStats();
console.log(stats);
// { totalRules: 3, totalAgents: 2, hasFallback: true }

const agents = router.listAgents();
console.log(agents);
// ['openai:gpt-4-turbo-preview', 'anthropic:claude-3-5-sonnet-20241022']

Chatbots

Crie IA conversacional com gerenciamento automático de memória.

Chatbot Básico

import { createChatbot, createAgent } from "mcp-agent-kit";

const bot = createChatbot({
  agent: createAgent({ provider: "openai" }),
  system: "You are a helpful assistant",
  maxHistory: 10,
});

await bot.chat("Hi, I am learning TypeScript");
await bot.chat("Can you help me with interfaces?");
await bot.chat("Thanks!");

Com Roteador

const bot = createChatbot({
  router: createLLMRouter({ rules: [...] }),
  maxHistory: 20
});

Gerenciamento de Memória

// Get conversation history
const history = bot.getHistory();

// Get statistics
const stats = bot.getStats();
console.log(stats);
// {
//   messageCount: 6,
//   userMessages: 3,
//   assistantMessages: 3,
//   oldestMessage: Date,
//   newestMessage: Date
// }

// Reset conversation
bot.reset();

// Update system prompt
bot.setSystemPrompt("You are now a Python expert");

Requisições de API

Requisições HTTP simplificadas com retry e timeout automáticos.

Requisição Básica

import { api } from "mcp-agent-kit";

const response = await api.get("https://api.example.com/data");
console.log(response.data);

Requisição POST

const response = await api.post(
  "https://api.example.com/users",
  { name: "John", email: "john@example.com" },
  {
    name: "create-user",
    headers: { "Content-Type": "application/json" },
  }
);

Com Retry e Timeout

const response = await api.request({
  name: "important-request",
  url: "https://api.example.com/data",
  method: "GET",
  timeout: 10000, // 10 seconds
  retries: 5, // 5 attempts
  query: { page: 1, limit: 10 },
});

Todos os Métodos HTTP

await api.get(url, config);
await api.post(url, body, config);
await api.put(url, body, config);
await api.patch(url, body, config);
await api.delete(url, config);

Configuração

Variáveis de Ambiente

Toda a configuração é opcional. Defina estas variáveis de ambiente ou passe-as no código:

# MCP Server
MCP_SERVER_NAME=my-server
MCP_PORT=7777

# Logging
LOG_LEVEL=info  # debug | info | warn | error

# LLM API Keys
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
GEMINI_API_KEY=...
OLLAMA_HOST=http://localhost:11434

Usando Arquivo .env

# .env
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
LOG_LEVEL=debug

O pacote carrega automaticamente arquivos .env usando dotenv.


Exemplos

Confira o diretório /examples para exemplos completos e funcionais:

  • basic-agent.ts - Uso simples de agente
  • smart-tool-calling.ts - Chamada inteligente de ferramentas com retry e cache
  • mcp-server.ts - Servidor MCP com ferramentas e recursos
  • mcp-server-websocket.ts - Servidor MCP com WebSocket
  • llm-router.ts - Roteamento inteligente entre LLMs
  • chatbot-basic.ts - Chatbot com memória de conversa
  • chatbot-with-router.ts - Chatbot usando roteador
  • api-requests.ts - Requisições HTTP com retry

Executando Exemplos

# Install dependencies
npm install

# Run an example
npx ts-node examples/basic-agent.ts

Referência da API

API do Agente

createAgent(config: AgentConfig)

Cria uma nova instância de agente de IA.

Parâmetros:

  • provider (obrigatório): Provedor LLM - "openai", "anthropic", "gemini" ou "ollama"
  • model (opcional): Nome do modelo (padrão é o do provedor)
  • temperature (opcional): Temperatura de amostragem 0-2 (padrão: 0.7)
  • maxTokens (opcional): Máximo de tokens na resposta (padrão: 2000)
  • apiKey (opcional): Chave de API (lê do ambiente se não for fornecida)
  • tools (opcional): Array de definições de ferramentas
  • system (opcional): Prompt de sistema
  • toolConfig (opcional): Configuração de chamada inteligente de ferramentas

Retorna: Instância de agente

Métodos:

  • chat(message: string): Promise<AgentResponse> - Envia uma mensagem e obtém resposta
  • executeTool(name: string, params: any): Promise<any> - Executa uma ferramenta diretamente

AgentResponse

Objeto de resposta de agent.chat():

{
  content: string;           // Response text
  toolCalls?: Array<{        // Tools that were called
    name: string;
    arguments: any;
  }>;
  usage?: {                  // Token usage
    promptTokens: number;
    completionTokens: number;
    totalTokens: number;
  };
}

API do Servidor MCP

createMCPServer(config: MCPServerConfig)

Cria uma nova instância de servidor MCP.

Parâmetros:

  • name (opcional): Nome do servidor (padrão: do ambiente ou "mcp-server")
  • port (opcional): Número da porta (padrão: 7777)
  • logLevel (opcional): Nível de log - "debug", "info", "warn", "error"
  • tools (opcional): Array de definições de ferramentas
  • resources (opcional): Array de definições de recursos

Retorna: Instância de servidor MCP

Métodos:

  • start(transport?: "stdio" | "websocket"): Promise<void> - Inicia o servidor

API do Roteador

createLLMRouter(config: LLMRouterConfig)

Cria uma nova instância de roteador LLM.

Parâmetros:

  • rules (obrigatório): Array de regras de roteamento
  • fallback (opcional): Configuração de provedor fallback
  • retryAttempts (opcional): Número de tentativas de retry (padrão: 3)
  • logLevel (opcional): Nível de log

Retorna: Instância de roteador

Métodos:

  • route(input: string): Promise<AgentResponse> - Roteia entrada para o LLM apropriado
  • getStats(): object - Obtém estatísticas do roteador
  • listAgents(): string[] - Lista todos os agentes configurados

API do Chatbot

createChatbot(config: ChatbotConfig)

Cria uma nova instância de chatbot com memória de conversa.

Parâmetros:

  • agent ou router (obrigatório): Instância de agente ou roteador
  • system (opcional): Prompt de sistema
  • maxHistory (opcional): Máximo de mensagens a manter (padrão: 10)

Retorna: Instância de chatbot

Métodos:

  • chat(message: string): Promise<AgentResponse> - Envia mensagem com contexto
  • getHistory(): ChatMessage[] - Obtém histórico da conversa
  • getStats(): object - Obtém estatísticas da conversa
  • reset(): void - Limpa histórico da conversa
  • setSystemPrompt(prompt: string): void - Atualiza prompt de sistema

Auxiliares de Requisição de API

api.request(config: APIRequestConfig)

Faça requisição HTTP com retry e timeout.

Parâmetros:

  • name (opcional): Nome da requisição para log
  • url (obrigatório): URL da requisição
  • method (opcional): Método HTTP (padrão: "GET")
  • headers (opcional): Cabeçalhos da requisição
  • query (opcional): Parâmetros de consulta
  • body (opcional): Corpo da requisição
  • timeout (opcional): Timeout em ms (padrão: 30000)
  • retries (opcional): Tentativas de retry (padrão: 3)

Retorna: Promise<APIResponse>

Métodos de Conveniência:

  • api.get(url, config?) - Requisição GET
  • api.post(url, body, config?) - Requisição POST
  • api.put(url, body, config?) - Requisição PUT
  • api.patch(url, body, config?) - Requisição PATCH
  • api.delete(url, config?) - Requisição DELETE

Uso Avançado

Provedor Personalizado

// Coming soon: Plugin system for custom providers

Middleware

// Coming soon: Middleware support for request/response processing

Respostas em Streaming

// Coming soon: Streaming support for real-time responses

Contribuindo

Contribuições são bem-vindas! Sinta-se à vontade para enviar um Pull Request.

  1. Faça um fork do repositório
  2. Crie sua branch de feature (git checkout -b feature/amazing-feature)
  3. Faça commit das suas alterações (git commit -m 'Add amazing feature')
  4. Envie para a branch (git push origin feature/amazing-feature)
  5. Abra um Pull Request

Licença

MIT © Dominique Kossi


Agradecimentos

  • Construído com TypeScript
  • Usa MCP SDK
  • Desenvolvido com OpenAI, Anthropic, Google e Ollama

Suporte


Feito por desenvolvedores, para desenvolvedores