spring-projects/spring-ai · error

Failed to serialize initResponse

Error message

Failed to serialize initResponse

What it means

A warning plus rethrown exception in WebFluxStreamableServerTransportProvider.handleInitResponse when serializing the JSONRPCResponse containing the InitializeResult fails with an IOException. The initialize handshake cannot complete, so the error propagates to the HTTP layer and the client's initialize call fails. This almost always means a component inside InitializeResult cannot be serialized to JSON.

Source

Thrown at mcp/transport/mcp-spring-webflux/src/main/java/org/springframework/ai/mcp/server/webflux/transport/WebFluxStreamableServerTransportProvider.java:474

		}
		var typeReference = new TypeRef<McpSchema.InitializeRequest>() {
		};
		McpSchema.InitializeRequest initializeRequest = this.jsonMapper.convertValue(jsonrpcRequest.params(),
				typeReference);
		McpStreamableServerSession.McpStreamableServerSessionInit init = this.sessionFactory
			.startSession(initializeRequest);
		this.sessions.put(init.session().getId(), init.session());
		if (this.sessionIdleTimeout != null) {
			this.sessionLastAccessTimes.put(init.session().getId(), Instant.now());
		}
		return init.initResult().map(initializeResult -> {
			McpSchema.JSONRPCResponse jsonrpcResponse = new McpSchema.JSONRPCResponse(McpSchema.JSONRPC_VERSION,
					jsonrpcRequest.id(), initializeResult, null);
			try {
				return this.jsonMapper.writeValueAsString(jsonrpcResponse);
			}
			catch (IOException e) {
				logger.warn("Failed to serialize initResponse", e);
				throw Exceptions.propagate(e);
			}
		})
			.flatMap(initResult -> ServerResponse.ok()
				.contentType(MediaType.APPLICATION_JSON)
				.header(HttpHeaders.MCP_SESSION_ID, init.session().getId())
				.bodyValue(initResult));
	}

	/**
	 * Records the current time as the last access time for the given session, so that an
	 * active session is not evicted as idle. No-op when idle eviction is disabled or the
	 * session is no longer tracked.
	 * @param sessionId the id of the session that was just accessed
	 */
	private void touchSession(String sessionId) {
		if (this.sessionIdleTimeout != null) {
			this.sessionLastAccessTimes.computeIfPresent(sessionId, (id, lastAccess) -> Instant.now());

View on GitHub (pinned to 98a7beda4f)

Solutions

  1. Inspect the IOException cause to find which field of InitializeResult fails to serialize
  2. Ensure all objects in serverInfo, capabilities, and tool schemas are simple JSON-mappable POJOs
  3. Avoid circular references or use DTOs for custom capability payloads
  4. Verify the configured JsonMapper (e.g. Jackson) handles all registered types

Example fix

// before
return new InitializeResult(PROTOCOL_VERSION,
    new ServerCapabilities.Builder().build(),
    Map.of("customObj", new SomeNonSerializableObject()), // breaks serialization
    serverInfo, instructions);
// after
return new InitializeResult(PROTOCOL_VERSION,
    new ServerCapabilities.Builder().build(),
    Map.of("custom", Map.of("key", "value")), // JSON-mappable
    serverInfo, instructions);
Defensive patterns

Strategy: try-catch

Validate before calling

// pre-validate InitializeResult payload is JSON-mappable
new ObjectMapper().writeValueAsString(initializeResult); // throws early if not

Try / catch

try {
    provider.handleInitRequest(...);
} catch (Exception e) {
    Throwable root = Exceptions.unwrap(e);
    log.error("Initialize failed (serialization?): {}", root.getMessage(), root);
}

Prevention

When it happens

Trigger: A custom capability, implementation info, or tool schema inside InitializeResult is not JSON-serializable (e.g. non-POJO objects, self-referencing structures, unsupported types); the JsonMapper misconfigured; serialization produced invalid state.

Common situations: Custom McpServerFeatures.SyncToolSpecification returning objects Jackson can't map; registering capabilities with exotic types; bugs in custom JsonMapper configuration.

Understand the failure class

Background: "JSON serialization failed", "not JSON serializable", "Failed to serialize": why JSON marshaling errors happen and how to fix them — this error's family across 46 libraries.

Related errors


AI-assisted analysis of spring-projects/spring-ai@98a7beda4f (2026-09-11). Data as JSON: /api/errors/83df3163854e8059. Report an issue: GitHub.