MCP client and server

llm4s-mcp speaks the Model Context Protocol in both directions: it connects to MCP servers and turns the tools they advertise into LLM4S tools an agent can call, and it serves your own tools to any MCP client, such as Claude Desktop or an IDE. The module is Beta.

  1. Installation
  2. When to use MCP
  3. Connecting to a server
  4. Giving an agent the server’s tools
  5. Tool hints and approval
  6. Using a server without an agent
  7. Exposing your own tools
  8. How failures surface
  9. Safety
  10. Samples

Installation

libraryDependencies += "org.llm4s" %% "llm4s-mcp" % "1.0.0"

It depends on llm4s-core only, not on the agent runtime: an MCP server’s tools are plain ToolFunctions, which an agent takes like any other.

When to use MCP

Use MCP when the tools you want already exist as an MCP server (a file system, a browser, a database, a SaaS API), or when one set of tools should serve several applications or assistants. A tool that only your application needs is simpler as a local tool: it runs in-process, with no server to start and no protocol in between. You can mix the two: an MCPToolRegistry holds local tools beside the servers’ tools.

Connecting to a server

An MCPServerConfig names a server and says how to reach it. There is one factory per transport:

Factory Transport Pick it when
MCPServerConfig.stdio(name, command) Starts the server as a subprocess and talks over its stdin and stdout The server is a local program, such as one run with npx or uvx
MCPServerConfig.streamableHTTP(name, url) Streamable HTTP (MCP 2025-03-26 and later): one endpoint for POST and GET The server runs elsewhere and speaks the current protocol; the usual choice
MCPServerConfig.sse(name, url) HTTP+SSE (MCP 2024-11-05): an event stream and a messages endpoint The server only speaks the older protocol

For both HTTP transports the client tries Streamable HTTP first. If the server refuses the initialize request with a 4xx status other than 401 or 403, it falls back to HTTP+SSE at the same URL.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import org.llm4s.llmconnect.auth.ApiKeyProvider
import org.llm4s.mcp.{ MCPHttpOptions, MCPServerConfig }

import java.nio.file.Paths
import scala.concurrent.duration._

// A local server, started as a subprocess. Pin the package version: `npx` runs whatever it fetches.
val browser = MCPServerConfig.stdio(
  name = "playwright",
  command = Seq("npx", "@playwright/mcp@0.0.86"),
  timeout = 60.seconds
)
// On Windows, `npx` is a .cmd script that a process cannot start directly: use Seq("cmd", "/c", "npx", ...)

// A remote server, sent a bearer key read from a file on every request (so a rotated key is picked up)
val search = MCPServerConfig.streamableHTTP(
  name = "search",
  url = "https://mcp.example.com/mcp",
  timeout = 60.seconds,
  http = MCPHttpOptions().withApiKey(ApiKeyProvider.file(Paths.get("/run/secrets/search-mcp-key")))
)

Every factory takes a timeout (30 seconds by default; the Playwright server above gets 60), the longest one request to the server may take, reply included. MCPHttpOptions also takes extra headers (withHeader) and an Llm4sHttpClient to send with (withHttpClient); its toString shows header names, never their values.

A stdio server does not inherit your environment. It starts with a small allowlist of variables (such as PATH, HOME, USER, LANG and TMPDIR, and their Windows counterparts) plus the ones you pass in env, so an OPENAI_API_KEY or a cloud credential of your application never reaches a third-party server unless you hand it over. Pass the variables the server needs in env; workingDirectory sets where it starts. inheritEnvironment = true passes the JVM’s whole environment, secrets included, and is only for a server you trust with all of them.

Giving an agent the server’s tools

MCPToolRegistry is a ToolRegistry: it holds your local tools and the tools of each configured server, and an agent takes it with withTools. Close it when you are done, which closes the connections to the servers:

1
2
3
4
5
6
7
8
9
10
11
12
13
import org.llm4s.agent.Agent
import org.llm4s.mcp.{ MCPServerConfig, MCPToolRegistry }

import scala.util.Using

val server = MCPServerConfig.streamableHTTP("demo", "http://localhost:8080/mcp")

val answer = Using.resource(new MCPToolRegistry(Seq(server), localTools = myTools)) { registry =>
  for {
    agent  <- Agent.builder("mcp-agent", client).withTools(registry).build()
    result <- agent.run("Convert 100 USD to EUR")
  } yield result.answer
}

How the registry behaves:

  • Startup. By default the constructor contacts every server, in parallel, and caches its tools; it returns once the slowest server has answered or timed out. Pass initializeOnStartup = false to connect on first use instead.
  • What an agent takes. An agent takes the registry’s tools, and their hints, when withTools is called. A server that is down at that moment gives that agent no tools, and tools a server adds later reach only agents built after them. The tools the agent did take find the server’s current tool each time they run, so they follow a reconnect.
  • Lookup order. A call runs the local tool of that name if there is one, otherwise the tool of the first configured server that advertises the name. A local tool shadows a server’s tool of the same name.
  • Caching. A server’s tool list is kept for cacheTTL (10 minutes by default) and fetched again on the next lookup after that. refreshCache() fetches again at once; clearCache() drops every cached list.
  • A server that is down. Its failure is logged and it contributes no tools, so the model is never offered a tool that cannot be called; the registry never throws during lookup. It is not dialled again for a while (1 second, doubling to at most a minute) so a dead server does not slow every call to a healthy one.
  • Health. healthCheck() contacts each server and returns a Map from server name to whether it answered.

MCPAgentExample runs an agent with a local weather tool and the tools of the demonstration server below.

Tool hints and approval

An MCP server can annotate each tool with hints: readOnlyHint, destructiveHint, idempotentHint and openWorldHint. The MCP specification says a client must treat these as untrusted unless the server is, so by default LLM4S ignores them and every MCP tool gets the conservative defaults: not read-only, destructive, not idempotent, open-world.

Set trustAnnotations = true on the config of a server you operate or have reviewed, and the registry passes that server’s hints to the agent. They matter with an approval middleware: ApprovalMiddleware.unlessReadOnly suspends the run for every tool call that is not read-only, so with untrusted hints every call to an MCP tool waits for a person:

1
2
3
4
5
6
7
8
9
10
11
12
13
import org.llm4s.agent.Agent
import org.llm4s.agent.graph.middleware.ApprovalMiddleware
import org.llm4s.mcp.{ MCPServerConfig, MCPToolRegistry }

// A server you run yourself: its read-only tools may skip approval
val internal = MCPServerConfig.streamableHTTP("internal", "http://localhost:8080/mcp", trustAnnotations = true)
val registry = new MCPToolRegistry(Seq(internal))

val agent = Agent
  .builder("reviewed-agent", client)
  .withTools(registry)
  .withMiddleware(ApprovalMiddleware.unlessReadOnly)
  .build()

Human review shows how a suspended run is approved, rejected or edited. ApprovalMiddleware and withMiddleware are @Experimental.

Using a server without an agent

To call a server’s tools yourself, construct an MCPClientImpl, run the handshake with initialize(), then list the tools with getTools(). Each tool calls the server when it runs. The client is not thread-safe, and close() closes its transport:

1
2
3
4
5
6
7
8
9
10
import org.llm4s.mcp.{ MCPClientImpl, MCPServerConfig }

val mcp = new MCPClientImpl(MCPServerConfig.streamableHTTP("demo", "http://localhost:8080/mcp"))

val toolNames = for {
  _     <- mcp.initialize()
  tools <- mcp.getTools()
} yield tools.map(_.name)

mcp.close()

MCPToolExample calls a local tool and a server’s tool through one MCPToolRegistry, without an agent.

Exposing your own tools

MCPServer serves a list of ToolFunctions over both transports at once: Streamable HTTP at {path} and HTTP+SSE at {path}/sse, for clients that only speak the older protocol. start() returns Left with the exception when the server cannot start, and stop() shuts it down:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import org.llm4s.mcp.{ MCPServer, MCPServerOptions, MCPToolAnnotations }
import org.llm4s.security.Secret

val options = MCPServerOptions(
  port = 8080,
  path = "/mcp",
  name = "orders",
  version = "1.0.0",
  apiKey = Some(Secret("change-me")) // load it from your secret store
)

// Advertise hints for the tools that only read; a tool without an entry is listed without annotations
val annotations = Map("get_order" -> MCPToolAnnotations(readOnlyHint = Some(true)))

val server = new MCPServer(options, myTools, annotations)
server.start() match {
  case Right(())   => println(s"MCP server listening on port ${server.boundPort}")
  case Left(error) => println(s"MCP server did not start: ${error.getMessage}")
}

What the options control:

  • Authentication. With apiKey set, every request must carry Authorization: Bearer <key>, and one without it is answered 401. Without a key the server logs a development-only warning.
  • Binding. The server binds 127.0.0.1 by default. start() refuses to bind any other host, such as 0.0.0.0, unless apiKey is set, so an unauthenticated server is never exposed to the network.
  • DNS rebinding. A server bound to a loopback host answers 403 to a request whose Host is not a loopback name (localhost, 127.0.0.1, [::1]) or one of allowedHosts. Any server answers 403 to a request whose Origin is present and neither loopback nor one of allowedOrigins; a request with no Origin (not from a browser) is not affected.
  • Sessions. A Streamable HTTP session expires after sessionIdleTimeout (30 minutes) unused, and at most maxSessions (1,000) are kept, the one unused longest giving way to a new one. A client whose session is gone is answered 404 and starts a new one.

DemonstrationMCPServer serves two tools with annotations on localhost, and AuthenticatedMCPServerSample adds a bearer key, with the configuration for Claude Desktop, Cursor and VS Code in its Scaladoc.

How failures surface

Every call that talks to a server returns a Result; none throws.

  • Connecting. initialize() returns a Left when the server cannot be reached, refuses the handshake, or answers with a protocol version the client does not support (it accepts 2025-06-18, 2025-03-26 and 2024-11-05).
  • Listing tools. getTools() returns a Left for any failure (a network error, a JSON-RPC error, a listing it cannot read), so a server that could not be reached is never mistaken for one with no tools (Right(Seq.empty)). In an MCPToolRegistry such a server contributes no tools, as above.
  • Calling a tool. A tool that reports a failure (an MCP result with isError: true) is a Left carrying the server’s text, as Tool call failed: <text>; so is a call the server did not answer in time. Through an agent it becomes a ToolCallError.HandlerError, which the model is shown so it can correct itself, as for a local tool (its section 4, “Returning a result or an error”).
  • Lost sessions. When a server answers 404 for the client’s session (it expired, or the server restarted), or a stdio server’s process has exited and been started again, the client runs the handshake again and retries the request once. Only those requests are retried, since the server never ran them; a request that failed in any other way may have run, and is never sent twice.
  • Interrupts. An interrupted initialize() or getTools() returns Left(CancelledError), and an interrupted tool call is reported as ToolCallError.Cancelled, never as a failed tool. Either way the interrupt flag stays set.

Safety

An MCP server’s tools run with that server’s privileges, not your application’s: a file-system server reads what its process can read, and a remote server does whatever its operator allows. Connect only to servers you would trust with the same access as your own code, pin the version of any server you start with npx or uvx, keep trustAnnotations off for servers you do not control, and put an approval middleware in front of tools that change things. Text a tool returns goes to the model like any other input, so a server can attempt a prompt injection through it; the guardrails apply to your users’ input and the model’s answers.

Samples

Sample What it shows
MCPAgentExample An agent with a local tool and a server’s tools
MCPToolExample Calling local and server tools through one registry, without an agent
DemonstrationMCPServer An MCPServer with two annotated tools, for the client samples to call
AuthenticatedMCPServerSample A server with a bearer key, and the client configuration for Claude Desktop, Cursor and VS Code
PlaywrightExample A stdio server: the Playwright browser tools, started with npx