MCP Tools

Connect AI agents to any MCP server with automatic transport selection

Connect agents to Model Context Protocol (MCP) servers to give them access to external tools, data, and services.

Diagram

MCP Integration

URL ends /sse

other URLs

🤖 Agent

🔌 MCP

Auto-detect

📡 SSE

🌊 HTTP-Streaming

✅ MCP Server

Quick Start

  1. Simple Usage
    typescript
    import { Agent, MCP } from 'praisonai';
    
    const mcp = new MCP('http://127.0.0.1:8080/sse');
    await mcp.initialize();
  2. With Configuration
    typescript
    const toolFunctions = Object.fromEntries(
      [...mcp].map(tool => [tool.name, async (args: any) => tool.execute(args)])
    );
    
    const agent = new Agent({
      instructions: 'You are a helpful assistant with access to MCP tools.',
      name: 'MCPAgent',
      tools: mcp.toOpenAITools(),
      toolFunctions,
    });
    
    const response = await agent.runSync('What tools are available?');
    console.log(response);
    
    await mcp.close();

Transport Selection

The MCP class picks the right transport automatically — no config objects needed.

Diagram

‘auto’ default

‘sse’

‘http-streaming’

Yes

No

URL provided

transport = ?

URL ends with /sse?

SSE transport

HTTP-Streaming transport

URL patterntransport paramTransport used
http://host/sse'auto' (default)SSE
http://host/api'auto' (default)HTTP-Streaming
any URL'sse'SSE (forced)
any URL'http-streaming'HTTP-Streaming (forced)

Examples

Auto (default)

typescript
import { Agent, MCP } from 'praisonai-ts';

async function main() {
  // URL ends with /sse → auto-selects SSE
  const mcp = new MCP('http://127.0.0.1:8080/sse');
  await mcp.initialize();
  console.log(`Transport: ${mcp.transportType}`); // 'sse'

  const toolFunctions = Object.fromEntries(
    [...mcp].map(tool => [tool.name, async (args: any) => tool.execute(args)])
  );

  const agent = new Agent({
    instructions: 'You are a helpful assistant.',
    name: 'AutoMCPAgent',
    tools: mcp.toOpenAITools(),
    toolFunctions,
  });

  const response = await agent.runSync('What tools are available?');
  console.log(response);

  await mcp.close();
}

main().catch(console.error);

Explicit SSE

typescript
import { Agent, MCP } from 'praisonai-ts';

async function main() {
  // Force SSE regardless of URL pattern
  const mcp = new MCP('http://127.0.0.1:8080/api', 'sse');
  await mcp.initialize();
  console.log(`Transport: ${mcp.transportType}`); // 'sse'

  const toolFunctions = Object.fromEntries(
    [...mcp].map(tool => [tool.name, async (args: any) => tool.execute(args)])
  );

  const agent = new Agent({
    instructions: 'You are a helpful assistant.',
    name: 'SSEMCPAgent',
    tools: mcp.toOpenAITools(),
    toolFunctions,
  });

  const response = await agent.runSync('List available tools');
  console.log(response);

  await mcp.close();
}

main().catch(console.error);

HTTP-Streaming

typescript
import { Agent, MCP } from 'praisonai-ts';

async function main() {
  // Force HTTP-Streaming
  const mcp = new MCP('http://127.0.0.1:8080/stream', 'http-streaming');
  await mcp.initialize();
  console.log(`Transport: ${mcp.transportType}`); // 'http-streaming'

  const toolFunctions = Object.fromEntries(
    [...mcp].map(tool => [tool.name, async (args: any) => tool.execute(args)])
  );

  const agent = new Agent({
    instructions: 'You are a helpful assistant.',
    name: 'HTTPMCPAgent',
    tools: mcp.toOpenAITools(),
    toolFunctions,
  });

  const response = await agent.runSync('What can you do?');
  console.log(response);

  await mcp.close();
}

main().catch(console.error);

Debug mode

typescript
import { Agent, MCP } from 'praisonai-ts';

async function main() {
  // Enable debug logging to see transport selection details
  const mcp = new MCP('http://127.0.0.1:8080/sse', 'auto', true);
  await mcp.initialize();
  // Logs: "MCP client initialized for URL: ... with transport: sse"
  // Logs: "Initialized MCP with N tools using sse transport"

  const agent = new Agent({
    instructions: 'You are a helpful assistant.',
    name: 'DebugMCPAgent',
    tools: mcp.toOpenAITools(),
    toolFunctions: Object.fromEntries(
      [...mcp].map(tool => [tool.name, async (args: any) => tool.execute(args)])
    ),
  });

  const response = await agent.runSync('Hello!');
  console.log(response);

  await mcp.close();
}

main().catch(console.error);

Configuration Options

OptionTypeDefaultDescription
urlstringrequiredMCP server URL
transportTransportType'auto'One of `’auto’ \‘sse’ \‘http-streaming’`
debugbooleanfalseLog transport selection and tool count
typescript
import { MCP, TransportType } from 'praisonai-ts';

const mcp = new MCP(
  'http://127.0.0.1:8080/stream',  // url
  'http-streaming',                  // transport
  true                               // debug
);

Instance API

Method / PropertyReturnsDescription
initialize()Promise<void>Connect and load tools from the server
close()Promise<void>Disconnect and release resources
toOpenAITools()OpenAITool[]Convert tools to OpenAI function-call format
[...mcp]MCPTool[]Iterate over available tools
mcp.toolsMCPTool[]Array of loaded tools (after initialize())
mcp.isConnectedbooleantrue after initialize(), false after close()
mcp.transportTypestring'sse', 'http-streaming', or 'not initialized'

New Exports

typescript
import { 
  MCP,                    // Unified MCP client (use this)
  TransportType,          // 'auto' | 'sse' | 'http-streaming'
  HTTPStreamingTransport, // Low-level transport (advanced use)
  MCPHttpStreaming,       // Standalone HTTP-Streaming client
  MCPTool,               // Tool type
  MCPToolInfo            // Tool info type
} from 'praisonai-ts';

Parity MCP Class (multi-server)

The MCP class exported from praisonai manages multiple named MCP servers and delegates to the real MCPClient (stdio / HTTP / SSE). It mirrors Python’s praisonaiagents.mcp and uses a connect / callTool API keyed by server name.

typescript
import { MCP } from 'praisonai';

const mcp = new MCP();

// Connect a named server (config is passed to MCPClient)
await mcp.connect('search', {
  transport: 'stdio',
  command: 'npx',
  args: ['-y', '@modelcontextprotocol/server-everything'],
});

// Call a tool on that server
const result = await mcp.callTool('search', 'echo', { message: 'hello' });
console.log(result);

console.log(mcp.listServers()); // ['search']

await mcp.disconnect('search');
MethodReturnsDescription
connect(name, config)Promise<void>Connect a named server. config matches MCPClientConfig
callTool(server, tool, args)Promise<any>Call tool on the named server with args
disconnect(name)Promise<void>Disconnect and remove the named server
listServers()string[]Names of connected servers

AI SDK-style: createMCP()

createMCP() from 'praisonai/ai' is the AI SDK-style client with full transport support.

typescript
import { createMCP } from 'praisonai/ai';

const client = await createMCP({
  transport: {
    type: 'stdio',
    command: 'my-mcp-server',
    args: ['--flag'],
    env: { API_KEY: '...' },
  },
});

const tools = await client.tools();
await client.close();

Transport types

MCPTransportConfig is a discriminated union on type.

typeFieldsNotes
'stdio'command, args?, env?Spawns a local server; env merged with process.env.
'sse'url, headers?, authProvider?authProvider is now forwarded (previously dropped, breaking OAuth).
'http'url, headers?, authProvider?Streamable HTTP transport.
'websocket'url, headers?WebSocket transport.

MCPConfig

OptionTypeDefaultDescription
transportMCPTransportConfigrequiredTransport configuration
namestring'praisonai-ts-mcp'Client name
versionstring'1.0.0'Client version
onUncaughtError(error: unknown) => void—Callback for uncaught errors

MCPClient methods

MethodReturnsDescription
tools()Promise<Record<string, MCPTool>>Load tools from the server
listResources()`Promise

| List available resources | | readResource(uri) | Promise

| Read a resource | | listPrompts() | Promise

| List available prompts | | getPrompt(name, args?) | Promise

| Get a prompt | | close() | Promise<void>` | Close the connection |


Best Practices

Always call close() when done

MCP connections stay open until explicitly closed. Always call await mcp.close() to release resources, especially in long-running applications or when switching servers.

typescript
const mcp = new MCP('http://localhost:8080/sse');
try {
  await mcp.initialize();
  // ... use the agent
} finally {
  await mcp.close();
}
Use debug=true when connecting a new server

Enable debug mode when first wiring up a new MCP server. It logs the selected transport and number of tools loaded, making misconfiguration easy to spot.

typescript
const mcp = new MCP('http://localhost:8080/api', 'auto', true);
await mcp.initialize();
// Console: "Initialized MCP with 5 tools using http-streaming transport"
Pass transport explicitly when URL patterns are ambiguous

Auto-detection relies on the URL ending in /sse. If your server URL doesn’t follow this convention, pass the transport explicitly to avoid surprises.

typescript
// This will use HTTP-Streaming even though it's an SSE server
const wrong = new MCP('https://api.example.com/sse/v2');  // auto = http-streaming

// Correct: pass transport explicitly
const right = new MCP('https://api.example.com/sse/v2', 'sse');
Prefer MCP over MCPHttpStreaming for new code

Use the unified MCP class for all new integrations. MCPHttpStreaming is a standalone client without auto-detection. Only use it if you specifically need direct HTTP-Streaming without the unified interface.


Related