|
| 1 | +// FR-MCP-REPL-001: YAML Protocol STDIO REPL Host - Server-side command dispatcher |
| 2 | +// FR-MCP-REPL-003: Command Namespace Parity - Request routing to client passthrough |
| 3 | +// TR-MCP-REPL-004: Command Registry and Dispatcher - Envelope-to-handler routing |
| 4 | +// TEST-MCP-REPL-001: REPL host processes well-formed YAML command envelopes |
| 5 | + |
| 6 | +namespace McpServer.Repl.Core; |
| 7 | + |
| 8 | +/// <summary> |
| 9 | +/// Dispatches parsed YAML envelopes to the appropriate handler and returns the response |
| 10 | +/// envelope. Responsible for routing <c>hello</c> handshakes and <c>request</c> envelopes |
| 11 | +/// by method namespace (currently <c>client.*.*</c> via <see cref="IGenericClientPassthrough"/>). |
| 12 | +/// Unknown namespaces produce a <c>method_not_found</c> error envelope so the agent loop |
| 13 | +/// can respond and continue instead of crashing. |
| 14 | +/// </summary> |
| 15 | +public interface IReplCommandDispatcher |
| 16 | +{ |
| 17 | + /// <summary> |
| 18 | + /// Dispatches a parsed YAML envelope and returns the response envelope (result or error). |
| 19 | + /// Never throws for recoverable dispatch failures — unexpected exceptions are caught and |
| 20 | + /// wrapped in an error envelope so the caller's read/write loop can remain alive. |
| 21 | + /// </summary> |
| 22 | + /// <param name="envelope">The inbound envelope to dispatch. Must have a non-null payload.</param> |
| 23 | + /// <param name="cancellationToken">Cancellation token propagated to handlers.</param> |
| 24 | + /// <returns>The response envelope to emit back to the caller.</returns> |
| 25 | + Task<IYamlEnvelope> DispatchAsync(IYamlEnvelope envelope, CancellationToken cancellationToken); |
| 26 | +} |
| 27 | + |
| 28 | +/// <summary> |
| 29 | +/// Default <see cref="IReplCommandDispatcher"/> implementation. Routes <c>hello</c> envelopes |
| 30 | +/// to a handshake response and <c>request</c> envelopes with the <c>client.<clientName>.<methodName></c> |
| 31 | +/// method shape to <see cref="IGenericClientPassthrough.InvokeAsync"/>. All other method |
| 32 | +/// namespaces produce a <c>method_not_found</c> error envelope. |
| 33 | +/// </summary> |
| 34 | +public sealed class ReplCommandDispatcher : IReplCommandDispatcher |
| 35 | +{ |
| 36 | + private const string ServerProtocolVersion = "1.0"; |
| 37 | + private readonly IGenericClientPassthrough _passthrough; |
| 38 | + |
| 39 | + /// <summary> |
| 40 | + /// Initializes a new <see cref="ReplCommandDispatcher"/>. |
| 41 | + /// </summary> |
| 42 | + /// <param name="passthrough">The generic client passthrough used to invoke <c>client.*.*</c> methods.</param> |
| 43 | + public ReplCommandDispatcher(IGenericClientPassthrough passthrough) |
| 44 | + { |
| 45 | + _passthrough = passthrough ?? throw new ArgumentNullException(nameof(passthrough)); |
| 46 | + } |
| 47 | + |
| 48 | + /// <inheritdoc /> |
| 49 | + public async Task<IYamlEnvelope> DispatchAsync(IYamlEnvelope envelope, CancellationToken cancellationToken) |
| 50 | + { |
| 51 | + ArgumentNullException.ThrowIfNull(envelope); |
| 52 | + |
| 53 | + switch (envelope.Type) |
| 54 | + { |
| 55 | + case "hello": |
| 56 | + return BuildHelloResponse(envelope.Payload as IHelloPayload); |
| 57 | + |
| 58 | + case "request": |
| 59 | + if (envelope.Payload is not IRequestPayload request) |
| 60 | + { |
| 61 | + return BuildError( |
| 62 | + requestId: "unknown", |
| 63 | + code: "invalid_envelope", |
| 64 | + message: "Request envelope is missing a request payload."); |
| 65 | + } |
| 66 | + return await DispatchRequestAsync(request, cancellationToken).ConfigureAwait(false); |
| 67 | + |
| 68 | + default: |
| 69 | + return BuildError( |
| 70 | + requestId: "unknown", |
| 71 | + code: "invalid_envelope", |
| 72 | + message: $"Unsupported envelope type: {envelope.Type}"); |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + private async Task<IYamlEnvelope> DispatchRequestAsync(IRequestPayload request, CancellationToken cancellationToken) |
| 77 | + { |
| 78 | + var method = request.Method ?? ""; |
| 79 | + |
| 80 | + if (method.StartsWith("client.", StringComparison.Ordinal)) |
| 81 | + { |
| 82 | + return await DispatchClientRequestAsync(request, cancellationToken).ConfigureAwait(false); |
| 83 | + } |
| 84 | + |
| 85 | + return BuildError( |
| 86 | + requestId: request.RequestId, |
| 87 | + code: "method_not_found", |
| 88 | + message: $"Method '{method}' is not routed by this dispatcher. " + |
| 89 | + "Supported namespaces: client.<clientName>.<methodName>."); |
| 90 | + } |
| 91 | + |
| 92 | + private async Task<IYamlEnvelope> DispatchClientRequestAsync(IRequestPayload request, CancellationToken cancellationToken) |
| 93 | + { |
| 94 | + // method shape: client.<clientName>.<methodName> |
| 95 | + var parts = request.Method.Split('.', 3); |
| 96 | + if (parts.Length != 3 || parts[0] != "client" || |
| 97 | + string.IsNullOrEmpty(parts[1]) || string.IsNullOrEmpty(parts[2])) |
| 98 | + { |
| 99 | + return BuildError( |
| 100 | + requestId: request.RequestId, |
| 101 | + code: "method_not_found", |
| 102 | + message: $"Method '{request.Method}' does not match the expected 'client.<clientName>.<methodName>' shape."); |
| 103 | + } |
| 104 | + |
| 105 | + var clientName = parts[1]; |
| 106 | + var methodName = parts[2]; |
| 107 | + var args = request.Params is null |
| 108 | + ? new Dictionary<string, object?>() |
| 109 | + : new Dictionary<string, object?>(request.Params, StringComparer.OrdinalIgnoreCase); |
| 110 | + |
| 111 | + try |
| 112 | + { |
| 113 | + var result = await _passthrough.InvokeAsync(clientName, methodName, args, cancellationToken).ConfigureAwait(false); |
| 114 | + return new YamlEnvelope |
| 115 | + { |
| 116 | + Type = "result", |
| 117 | + Payload = new ResultPayload |
| 118 | + { |
| 119 | + RequestId = request.RequestId, |
| 120 | + Result = result, |
| 121 | + }, |
| 122 | + }; |
| 123 | + } |
| 124 | + catch (OperationCanceledException) |
| 125 | + { |
| 126 | + throw; |
| 127 | + } |
| 128 | + catch (Exception ex) |
| 129 | + { |
| 130 | + return BuildError( |
| 131 | + requestId: request.RequestId, |
| 132 | + code: "method_invocation_error", |
| 133 | + message: ex.Message, |
| 134 | + details: new Dictionary<string, object?> |
| 135 | + { |
| 136 | + ["clientName"] = clientName, |
| 137 | + ["methodName"] = methodName, |
| 138 | + ["exceptionType"] = ex.GetType().FullName, |
| 139 | + }); |
| 140 | + } |
| 141 | + } |
| 142 | + |
| 143 | + private static IYamlEnvelope BuildHelloResponse(IHelloPayload? request) |
| 144 | + { |
| 145 | + var capabilities = new List<string> { "client-passthrough" }; |
| 146 | + if (request?.Capabilities is not null) |
| 147 | + { |
| 148 | + capabilities.AddRange(request.Capabilities); |
| 149 | + } |
| 150 | + |
| 151 | + return new YamlEnvelope |
| 152 | + { |
| 153 | + Type = "hello", |
| 154 | + Payload = new HelloPayload |
| 155 | + { |
| 156 | + ProtocolVersion = ServerProtocolVersion, |
| 157 | + Capabilities = capabilities, |
| 158 | + }, |
| 159 | + }; |
| 160 | + } |
| 161 | + |
| 162 | + private static IYamlEnvelope BuildError( |
| 163 | + string requestId, |
| 164 | + string code, |
| 165 | + string message, |
| 166 | + IReadOnlyDictionary<string, object?>? details = null) |
| 167 | + { |
| 168 | + return new YamlEnvelope |
| 169 | + { |
| 170 | + Type = "error", |
| 171 | + Payload = new ErrorPayload |
| 172 | + { |
| 173 | + RequestId = requestId, |
| 174 | + Code = code, |
| 175 | + Message = message, |
| 176 | + Details = details, |
| 177 | + }, |
| 178 | + }; |
| 179 | + } |
| 180 | +} |
0 commit comments