# MCP servers

Let a model use the tools of an MCP server, from your own code.

An MCP server offers tools: read a file, query a database, open a ticket. The model never reaches the server itself. Your code starts it, hands its tools to the model in `tools`, and runs each call the model asks for. The request is the one [Tools and function calling](/docs/tools) sets out; the tools come from the server instead of your own code.

1. [Install the libraries](#1-install-the-libraries).
2. [Start the server and read its tools](#2-start-the-server-and-read-its-tools).
3. [Run the calls the model asks for](#3-run-the-calls-the-model-asks-for).
4. [Read what each turn cost](#4-read-what-each-turn-cost).

## 1. Install the libraries

The samples start the filesystem MCP server, which reads the files in one folder, with `npx`: Node must be on your machine whatever language you write in.

| Tab | Install line |
|---|---|
| Python | `pip install mcp openai` |
| JavaScript | `npm install @modelcontextprotocol/client openai` |
| Go | `go get github.com/modelcontextprotocol/go-sdk/mcp github.com/openai/openai-go/v3` |
| cURL | none: it sends the first turn only |

## 2. Start the server and read its tools

The MCP library starts the server as a child process and lists its tools. Each tool carries a name, a description and a JSON Schema of its arguments: the three parts of a function in `tools`, under other names.

| MCP tool | Function in `tools` |
|---|---|
| `name` | `function.name` |
| `description` | `function.description` |
| `inputSchema` | `function.parameters`, without its `$schema` line |

The filesystem server offers fourteen tools, and some of them write, move and edit files. The samples pass three that only read.

<div class="dont">
<p>Don't hand the model every tool a server offers. It can call any tool it is given, and a call to <code>write_file</code> writes the file.</p>
</div>

<div class="do">
<p>Pass the tools the job needs, by name, as <code>ALLOWED</code> does below.</p>
</div>

## 3. Run the calls the model asks for

Each turn sends the conversation and the tools to [`POST /v1/chat/completions`](/docs/reference/chat-completions). When the answer carries `tool_calls`, the code runs each call on the server, adds the text it returned as a `tool` message, and sends the conversation again. When the answer carries words, it prints them and stops. `MAX_TURNS` caps the loop.

```python
import asyncio
import json
import os
from mcp import Client, StdioServerParameters
from mcp.types import TextContent
from openai import AsyncOpenAI

API_KEY = os.environ["OPENDUNES_API_KEY"]
BASE_URL = "https://opendunes.com/v1"
MODEL = "anthropic/claude-sonnet-4.5"
FOLDER = "."
PROMPT = "Which files in this folder hold Python code?"
MAX_TURNS = 10
ALLOWED = {"list_directory", "read_text_file", "search_files"}

SERVER = StdioServerParameters(
    command="npx",
    args=["-y", "@modelcontextprotocol/server-filesystem", FOLDER],
)

client = AsyncOpenAI(base_url=BASE_URL, api_key=API_KEY)


def as_function(tool):
    parameters = dict(tool.input_schema)
    parameters.pop("$schema", None)
    return {
        "type": "function",
        "function": {
            "name": tool.name,
            "description": tool.description or "",
            "parameters": parameters,
        },
    }


def as_text(result):
    texts = [b.text for b in result.content if isinstance(b, TextContent)]
    return "\n".join(texts)


async def main():
    async with Client(SERVER) as server:
        listed = await server.list_tools()
        tools = [as_function(t) for t in listed.tools if t.name in ALLOWED]
        messages = [{"role": "user", "content": PROMPT}]

        for _ in range(MAX_TURNS):
            reply = await client.chat.completions.create(
                model=MODEL,
                messages=messages,
                tools=tools,
            )
            message = reply.choices[0].message
            print(reply.usage.cost)
            if not message.tool_calls:
                print(message.content)
                break
            messages.append(message)
            for call in message.tool_calls:
                args = json.loads(call.function.arguments)
                result = await server.call_tool(call.function.name, args)
                messages.append(
                    {
                        "role": "tool",
                        "tool_call_id": call.id,
                        "content": as_text(result),
                    }
                )


asyncio.run(main())
```

```javascript
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import OpenAI from "openai";

const API_KEY = process.env.OPENDUNES_API_KEY;
const BASE_URL = "https://opendunes.com/v1";
const MODEL = "anthropic/claude-sonnet-4.5";
const FOLDER = ".";
const PROMPT = "Which files in this folder hold Python code?";
const MAX_TURNS = 10;
const ALLOWED = ["list_directory", "read_text_file", "search_files"];

const server = new Client({ name: "opendunes-recipe", version: "1.0.0" });
await server.connect(
  new StdioClientTransport({
    command: "npx",
    args: ["-y", "@modelcontextprotocol/server-filesystem", FOLDER],
  }),
);

const client = new OpenAI({ baseURL: BASE_URL, apiKey: API_KEY });

const { tools: listed } = await server.listTools();
const tools = listed
  .filter((tool) => ALLOWED.includes(tool.name))
  .map((tool) => {
    const { $schema, ...parameters } = tool.inputSchema;
    return {
      type: "function",
      function: {
        name: tool.name,
        description: tool.description ?? "",
        parameters,
      },
    };
  });

const messages = [{ role: "user", content: PROMPT }];

for (let turn = 0; turn < MAX_TURNS; turn++) {
  const reply = await client.chat.completions.create({
    model: MODEL,
    messages,
    tools,
  });
  const message = reply.choices[0].message;
  console.log(reply.usage.cost);
  if (!message.tool_calls?.length) {
    console.log(message.content);
    break;
  }
  messages.push(message);
  for (const call of message.tool_calls) {
    const result = await server.callTool({
      name: call.function.name,
      arguments: JSON.parse(call.function.arguments),
    });
    const text = result.content
      .filter((block) => block.type === "text")
      .map((block) => block.text)
      .join("\n");
    messages.push({ role: "tool", tool_call_id: call.id, content: text });
  }
}

await server.close();
```

```go
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"os"
	"os/exec"

	"github.com/modelcontextprotocol/go-sdk/mcp"
	"github.com/openai/openai-go/v3"
	"github.com/openai/openai-go/v3/option"
)

const (
	baseURL  = "https://opendunes.com/v1"
	model    = "anthropic/claude-sonnet-4.5"
	folder   = "."
	prompt   = "Which files in this folder hold Python code?"
	maxTurns = 10
)

func main() {
	apiKey := os.Getenv("OPENDUNES_API_KEY")
	allowed := map[string]bool{
		"list_directory": true,
		"read_text_file": true,
		"search_files":   true,
	}
	ctx := context.Background()

	server := mcp.NewClient(
		&mcp.Implementation{Name: "opendunes-recipe", Version: "1.0.0"},
		nil,
	)
	transport := &mcp.CommandTransport{
		Command: exec.Command(
			"npx", "-y", "@modelcontextprotocol/server-filesystem", folder,
		),
	}
	session, err := server.Connect(ctx, transport, nil)
	if err != nil {
		panic(err)
	}
	defer session.Close()

	listed, err := session.ListTools(ctx, nil)
	if err != nil {
		panic(err)
	}
	var tools []openai.ChatCompletionToolUnionParam
	for _, tool := range listed.Tools {
		if !allowed[tool.Name] {
			continue
		}
		var schema map[string]any
		raw, _ := json.Marshal(tool.InputSchema)
		json.Unmarshal(raw, &schema)
		delete(schema, "$schema")
		tools = append(tools, openai.ChatCompletionFunctionTool(
			openai.FunctionDefinitionParam{
				Name:        tool.Name,
				Description: openai.String(tool.Description),
				Parameters:  schema,
			},
		))
	}

	client := openai.NewClient(
		option.WithBaseURL(baseURL),
		option.WithAPIKey(apiKey),
	)
	params := openai.ChatCompletionNewParams{
		Model: model,
		Messages: []openai.ChatCompletionMessageParamUnion{
			openai.UserMessage(prompt),
		},
		Tools: tools,
	}

	for turn := 0; turn < maxTurns; turn++ {
		reply, err := client.Chat.Completions.New(ctx, params)
		if err != nil {
			panic(err)
		}
		message := reply.Choices[0].Message
		fmt.Println(reply.Usage.JSON.ExtraFields["cost"].Raw())
		if len(message.ToolCalls) == 0 {
			fmt.Println(message.Content)
			return
		}
		params.Messages = append(params.Messages, message.ToParam())
		for _, call := range message.ToolCalls {
			var args map[string]any
			json.Unmarshal([]byte(call.Function.Arguments), &args)
			result, err := session.CallTool(ctx, &mcp.CallToolParams{
				Name:      call.Function.Name,
				Arguments: args,
			})
			if err != nil {
				panic(err)
			}
			text := ""
			for _, block := range result.Content {
				if t, ok := block.(*mcp.TextContent); ok {
					text += t.Text
				}
			}
			answer := openai.ToolMessage(text, call.ID)
			params.Messages = append(params.Messages, answer)
		}
	}
}
```

```bash cURL
ADDRESS="https://opendunes.com/v1/chat/completions"
MODEL="anthropic/claude-sonnet-4.5"
PROMPT="Which files in this folder hold Python code?"

curl "$ADDRESS" \
  -H "Authorization: Bearer $OPENDUNES_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "'"$MODEL"'",
    "messages": [
      {
        "role": "user",
        "content": "'"$PROMPT"'"
      }
    ],
    "tools": [
      {
        "type": "function",
        "function": {
          "name": "list_directory",
          "description": "List the files and folders at a path.",
          "parameters": {
            "type": "object",
            "properties": {
              "path": {
                "type": "string"
              }
            },
            "required": ["path"]
          }
        }
      }
    ]
  }'
```

cURL speaks no MCP: its tab is the first turn, with one of the server's tools written out by hand. Its answer carries the `tool_calls` your code runs on the server.

## 4. Read what each turn cost

Each turn is a request of its own, charged as one, and each sample prints its charge in DA as it goes. The tools' descriptions and schemas are prompt tokens on every turn, and so is every file the model has read so far. A server with many tools costs more on each turn than the same job with three.

<div class="good-to-know">
<p>A request never names an MCP server. Your code, or your coding agent, runs the server and sends its tools; OpenDunes sees functions in <code>tools</code>, as from any other code.</p>
</div>

## In a coding agent

A coding agent is an MCP client already: add the server in the agent's own settings, and the agent does steps 2 and 3 for you, on the model you set it up with. Setting each agent up on OpenDunes: [Coding agents](/docs/coding-agents).

| Agent | Reads MCP servers from |
|---|---|
| Claude Code | `.mcp.json` at the root of your project, or `claude mcp add` |
| Claude Desktop | `claude_desktop_config.json`, opened from *Settings*, *Developer*, *Edit Config* |
| Cursor | `~/.cursor/mcp.json`, or `.cursor/mcp.json` in one project |

The OpenDunes docs answer as an MCP server of their own, with no key: [MCP · the docs](/docs/mcp-docs).

## Errors

| Status | Means | Do |
|---|---|---|
| 401 | the key is missing, wrong, paused, revoked or expired | check `OPENDUNES_API_KEY` is set |
| 402 | the balance is at zero or below, cannot pay the request's hold, or the key's cap is spent | make a deposit, or raise the cap |

A server that fails to start stops the sample before any request, and costs nothing. Every other status: [Errors and retries](/docs/errors-and-retries).

Next: [Claude Code](/docs/cookbook/claude-code) · [Cursor](/docs/cookbook/cursor)
