covers:
- src/serena/mcp.py
- src/serena/project_server.py
- scripts/mcp_server.py
- server.json
Serena MCP Server Flow
Overview
Serena's MCP entrypoint is the start-mcp-server CLI command reached by scripts/mcp_server.py, which only imports serena.cli.top_level and calls top_level.start_mcp_server(). The command implementation in src/…/cli.py configures logging before the MCP server is created: logs go to stderr rather than stdout because stdio MCP uses stdout for protocol traffic, and a MemoryLogHandler is retained so the agent/dashboard can show runtime logs. The public MCP registry metadata in server.json advertises the package as serena-agent, starts it with the positional command start-mcp-server, defaults to stdio transport, and exposes optional package arguments such as --project-from-cwd and --context.
Startup configuration flows from the CLI into SerenaMCPFactory in src/…/mcp.py. The CLI accepts an explicit project (--project, deprecated --project-file, or positional project), optional --project-from-cwd, context name/path, mode overrides, language backend, agent interface, dashboard/log-window flags, log level, LSP tracing, tool timeout, and transport/host/port. When --project-from-cwd is used, src/…/cli.py rejects any simultaneous explicit project, looks for a project root from the current working directory, and, if none is found, records a project_activation_error that is passed into the agent so the MCP client can be told that no project was activated and should use the activation tool.
SerenaMCPFactory.__init__ loads the requested SerenaAgentContext immediately and stores the selected transport and startup project. create_mcp_server() then loads SerenaConfig.from_config_file() and applies CLI overrides directly onto that config before constructing a SerenaAgent with the selected project, context, modes, memory log handler, and optional project activation error. Fatal exceptions during config/agent creation are rendered through show_fatal_exception_safe() and re-raised, so server startup fails rather than serving a partially initialized agent.
The returned MCP server is an MCP SDK MCPServer named Serena with Serena's package version, website URL, initial instructions from agent.create_connection_prompt(), and server_lifespan as its lifespan hook. src/…/mcp.py also patches the MCP SDK's logging setup so it does not overwrite Serena's logging, and for HTTP-style transports the CLI runs the server inside uvicorn_ignore_logging_config_context(), which temporarily replaces uvicorn.Config so Uvicorn cannot reset log configuration. The CLI runs stdio with server.run(transport="stdio"); SSE and streamable HTTP use the configured host/port.
MCP tool exposure is deferred to SerenaMCPFactory.server_lifespan(). For stdio this lifespan is effectively process-wide, while for SSE/streamable HTTP the comment notes it runs once per client connection. On each lifespan setup, the factory chooses OpenAI-compatible schema sanitization for contexts named chatgpt, codex, or oaicompat-agent, reads structured_tool_output from the agent context, clears the MCP SDK's internal tool registry, and repopulates it from agent.get_exposed_tool_instances(). Each Serena Tool is wrapped as a SerenaFastMCPTool, which builds the MCP parameter schema from the tool's apply metadata, adds docstring parameter descriptions, optionally rewrites schema constructs unsupported by OpenAI tools, and uses context-level tool_description_overrides when present. Tool annotations are derived from tool.can_edit(): read-only tools are advertised with read_only_hint, while editing-capable tools are marked destructive.
Client tool calls route through SerenaFastMCPTool.run(). Before delegating to the MCP SDK, it rewrites any supported parameter aliases from tool.get_param_aliases() to canonical parameter names. The wrapper's execute_fn invokes tool.apply_ex(log_call=True, catch_exceptions=False, **kwargs) on the underlying Serena tool. Serena ToolCallError is converted into MCP ToolError with the user-facing error message; other exceptions are left to the MCP SDK/server layer. The wrapper sets context_kwarg="mcp_ctx" to match Tool.apply_ex's expected MCP context keyword, allowing Serena tools that accept MCP context to receive it.
Shutdown behavior depends on transport. In server_lifespan() teardown, stdio logs server shutdown and calls agent.on_shutdown(); non-stdio transports only log that a client disconnected, leaving the singleton agent instance alive for future connections. This means long-lived HTTP/SSE servers keep agent state across client sessions, while stdio servers clean up when the single MCP process exits.
src/…/project_server.py is a companion HTTP flow used when a Serena MCP session needs to query other registered projects, especially for LSP-backed symbolic access that cannot safely share a single active project. ProjectServer builds a headless SerenaAgent from SerenaConfig.from_config_file().with_headless_mode_overrides(), forces the built-in language backend to LSP, and serves Flask endpoints on SerenaPorts.PROJECT_SERVER_PORT by default. If bound to localhost/127.0.0.1, Flask TRUSTED_HOSTS is restricted to local hostnames. Every route is protected by a bearer token from serena_config.auth_secret; requests without an exact Authorization: Bearer <secret> header are rejected with 401 before payload parsing or project access.
The project server exposes /heartbeat, /query_project, and /call_facade_method. Projects are loaded on demand through SerenaConfig.get_registered_project(), keyed by project root, cached in memory, and initialized with project.create_language_server_manager(). Project loading uses a global dictionary lock plus per-project load locks so independent projects can load concurrently while duplicate loads of the same root are coalesced. Actual tool/facade execution uses _active_project_lock around agent.active_project_context(project) because the active project is process-wide state but tool execution can continue on the agent's task executor thread. /query_project only executes read-only tools and rejects non-read-only tool names; /call_facade_method runs REPL facade methods via agent.execute_task() and returns pickled results to the trusted local client. Facade errors are returned as plain-text HTTP 400 responses rather than generic Flask error pages.
ProjectServerClient is the in-process client used by Serena tools and REPL support to reach that companion server. It derives the base URL from host/port, sets request timeout to serena_config.tool_timeout - 1, sends the shared bearer token, and verifies availability with /heartbeat during construction. Its query_project() mirrors QueryProjectRequest and returns response text after raise_for_status(). Its call_facade_method() posts JSON-serializable call data and unpickles the binary result; non-OK responses are converted to ValueError with the first 2000 response characters.
Coupling
- If server.json package arguments change, verify src/…/cli.py still accepts the advertised invocation. The registry metadata currently starts
serena-agentwithstart-mcp-server, optional--project-from-cwd, and optional--context; a mismatch would make MCP clients install a package that cannot start the server. - If
Tool.apply_exchanges its MCP context keyword or exception contract, update src/…/mcp.py.SerenaFastMCPToolhard-codescontext_kwarg="mcp_ctx"and only translatesToolCallErrorinto MCPToolError, so renamed context parameters or new user-facing error types would change client-visible behavior. - If tool schemas or context names change, verify src/…/mcp.py schema generation and context checks. OpenAI-compatible sanitization is enabled only for context names
chatgpt,codex, andoaicompat-agent, and structured output is read fromagent.get_context().structured_tool_outputwhen tools are installed. - If
SerenaConfig.auth_secret,tool_timeout, or project registration semantics change, update both sides of src/…/project_server.py. The server authenticates all routes againstauth_secret, whileProjectServerClientsends that same secret and derives its request timeout fromtool_timeout - 1; project lookup also assumesget_registered_project()can resolve either a project name or root path. - If the active-project model in
SerenaAgentchanges, revisitProjectServer._query_project()and_call_facade_method()in src/…/project_server.py. Both serialize execution with_active_project_lockbecause active project is process-wide state; removing or changing that invariant may allow more concurrency, but dropping the lock without an agent change would route concurrent requests to the wrong project.
Risks
- src/…/mcp.py mutates MCP SDK internals with
mcp._tool_manager._tools = {}and direct assignment per tool. If the SDK changes its private tool manager structure, Serena may start with no tools or stale tools even though the server itself launches. - src/…/mcp.py globally monkeypatches
server.configure_loggingand temporarily replacesuvicorn.Config. If either patch is left inconsistent with upstream APIs, HTTP transports can reset logging or fail during server creation; stdio clients are especially sensitive because stdout must remain protocol-only. - src/…/project_server.py pickles
/call_facade_methodresults andProjectServerClient.call_facade_method()unpickles them. This is intended for a trusted local Serena process protected by the shared bearer token; exposing the project server beyond trusted localhost or leakingauth_secretwould turn that endpoint into unsafe code/data deserialization surface. - src/…/project_server.py runs Flask with
threaded=Truewhile sharing oneSerenaAgent. The_active_project_lockprevents cross-project active-state corruption during tool and facade execution; any new endpoint that entersactive_project_context()without that lock can make concurrent requests execute against or restore the wrong project.