MCP

createMcpAdapter() makes an MCP server's tools available to your agent. Your code connects and authenticates the MCP client; the adapter supplies tools and instructions to libfx.

Connect a server

Install the MCP client alongside libfx:

npm install libfx@0.0.12 @modelcontextprotocol/sdk@1

Set MCP_SERVER_URL to your server's Streamable HTTP endpoint. This example uses a server that accepts unauthenticated connections:

import { Client } from '@modelcontextprotocol/sdk/client/index.js'
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'
import { createFxAgent } from 'libfx'
import { createMcpAdapter } from 'libfx/mcp'

const client = new Client({ name: 'libfx-example', version: '1.0.0' })
let agent
try {
  await client.connect(new StreamableHTTPClientTransport(
    new URL(process.env.MCP_SERVER_URL),
  ))
  const mcp = await createMcpAdapter(client)
  agent = await createFxAgent({
    apiKey: process.env.AI_GATEWAY_API_KEY,
    tools: mcp.tools,
    instructions: mcp.instructions,
  })
  const turn = agent.prompt('Use the available tools to show what this server offers.')
  for await (const event of turn) {
    if (event.type === 'text_delta') process.stdout.write(event.delta)
  }
  await turn.result
} finally {
  try {
    await agent?.close()
  } finally {
    await client.close()
  }
}

libfx also accepts connected clients using stdio instead of HTTP.

Authenticate the connection

For a server that accepts a bearer token, set MCP_SERVER_TOKEN and replace the transport above with:

const transport = new StreamableHTTPClientTransport(
  new URL(process.env.MCP_SERVER_URL),
  { requestInit: { headers: { Authorization: `Bearer ${process.env.MCP_SERVER_TOKEN}` } } },
)
await client.connect(transport)

For OAuth, configure the MCP client's authProvider. Authentication belongs to that connection; the AI Gateway key is only for model requests.

Include resources and prompts

Pass resources and prompts to createMcpAdapter() to include their text in the agent's instructions. Use prefix to distinguish tools when combining servers. See the adapter options.