Tao Wu
Tao Wu

Reputation: 11

JAVA MCP SDK WebFlux Server Transport sendMessage is Broadcasts?

Why is this place broadcast to all sessions, if one MCPClient initiates the call, other McPclients will also receive the call results of other clients? thanks for help

    /**
     * Broadcasts a message to all connected clients through their SSE connections. The
     * message is serialized to JSON and sent as an SSE event with type "message". If any
     * errors occur during sending to a particular client, they are logged but don't
     * prevent sending to other clients.
     * @param message The JSON-RPC message to broadcast to all connected clients
     * @return A Mono that completes when the broadcast attempt is finished
     */
    @Override
    public Mono<Void> sendMessage(McpSchema.JSONRPCMessage message) {
        return Mono.fromRunnable(() -> {
            if (sessions.isEmpty()) {
                logger.debug("No active sessions to broadcast message to");
                return;
            }

            try {
                String jsonText = objectMapper.writeValueAsString(message);
                logger.debug("Attempting to broadcast message to {} active sessions", sessions.size());

                sessions.values().forEach(session -> {
                    try {
                        session.sseBuilder.id(session.id).event(MESSAGE_EVENT_TYPE).data(jsonText);
                    }
                    catch (Exception e) {
                        logger.error("Failed to send message to session {}: {}", session.id, e.getMessage());
                        session.sseBuilder.error(e);
                    }
                });
            }
            catch (IOException e) {
                logger.error("Failed to serialize message: {}", e.getMessage());
            }
        });
    }

Upvotes: 0

Views: 26

Answers (0)

Related Questions