Skip to content

Backfills trace injection test and migrates from request.params to request.params._meta #360

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 29, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 12 additions & 12 deletions src/ModelContextProtocol/Diagnostics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,22 +50,19 @@ private static void ExtractContext(object? message, string fieldName, out string
fieldValues = null;
fieldValue = null;

JsonNode? parameters = null;
JsonNode? meta = null;
switch (message)
{
case JsonRpcRequest request:
parameters = request.Params;
meta = request.Params?["_meta"];
break;

case JsonRpcNotification notification:
parameters = notification.Params;
break;

default:
meta = notification.Params?["_meta"];
break;
}

if (parameters?[fieldName] is JsonValue value && value.GetValueKind() == JsonValueKind.String)
if (meta?[fieldName] is JsonValue value && value.GetValueKind() == JsonValueKind.String)
{
fieldValue = value.GetValue<string>();
}
Expand All @@ -89,14 +86,17 @@ private static void InjectContext(object? message, string key, string value)
case JsonRpcNotification notification:
parameters = notification.Params;
break;

default:
break;
}

if (parameters is JsonObject jsonObject && jsonObject[key] == null)
// Replace any params._meta with the current value
if (parameters is JsonObject jsonObject)
{
jsonObject[key] = value;
if (jsonObject["_meta"] is not JsonObject meta)
{
meta = new JsonObject();
jsonObject["_meta"] = meta;
}
meta[key] = value;
}
}

Expand Down
46 changes: 42 additions & 4 deletions tests/ModelContextProtocol.Tests/DiagnosticTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
using OpenTelemetry.Trace;
using System.Diagnostics;
using System.IO.Pipelines;
using System.Text;
using System.Text.Json;

namespace ModelContextProtocol.Tests;

Expand All @@ -14,6 +16,7 @@ public class DiagnosticTests
public async Task Session_TracksActivities()
{
var activities = new List<Activity>();
var clientToServerLog = new List<string>();

using (var tracerProvider = OpenTelemetry.Sdk.CreateTracerProviderBuilder()
.AddSource("Experimental.ModelContextProtocol")
Expand All @@ -28,7 +31,7 @@ await RunConnected(async (client, server) =>

var tool = tools.First(t => t.Name == "DoubleValue");
await tool.InvokeAsync(new() { ["amount"] = 42 }, TestContext.Current.CancellationToken);
});
}, clientToServerLog);
}

Assert.NotEmpty(activities);
Expand Down Expand Up @@ -64,6 +67,11 @@ await RunConnected(async (client, server) =>

Assert.Equal(clientListToolsCall.SpanId, serverListToolsCall.ParentSpanId);
Assert.Equal(clientListToolsCall.TraceId, serverListToolsCall.TraceId);

// Validate that the client trace context encoded to request.params._meta[traceparent]
using var listToolsJson = JsonDocument.Parse(clientToServerLog.First(s => s.Contains("\"method\":\"tools/list\"")));
var metaJson = listToolsJson.RootElement.GetProperty("params").GetProperty("_meta").GetRawText();
Assert.Equal($$"""{"traceparent":"00-{{clientListToolsCall.TraceId}}-{{clientListToolsCall.SpanId}}-01"}""", metaJson);
}

[Fact]
Expand All @@ -80,7 +88,7 @@ await RunConnected(async (client, server) =>
{
await client.CallToolAsync("Throw", cancellationToken: TestContext.Current.CancellationToken);
await Assert.ThrowsAsync<McpException>(() => client.CallToolAsync("does-not-exist", cancellationToken: TestContext.Current.CancellationToken));
});
}, new List<string>());
}

Assert.NotEmpty(activities);
Expand Down Expand Up @@ -120,11 +128,12 @@ await RunConnected(async (client, server) =>
Assert.Equal("-32602", doesNotExistToolClient.Tags.Single(t => t.Key == "rpc.jsonrpc.error_code").Value);
}

private static async Task RunConnected(Func<IMcpClient, IMcpServer, Task> action)
private static async Task RunConnected(Func<IMcpClient, IMcpServer, Task> action, List<string> clientToServerLog)
{
Pipe clientToServerPipe = new(), serverToClientPipe = new();
StreamServerTransport serverTransport = new(clientToServerPipe.Reader.AsStream(), serverToClientPipe.Writer.AsStream());
StreamClientTransport clientTransport = new(clientToServerPipe.Writer.AsStream(), serverToClientPipe.Reader.AsStream());
StreamClientTransport clientTransport = new(new LoggingStream(
clientToServerPipe.Writer.AsStream(), clientToServerLog.Add), serverToClientPipe.Reader.AsStream());

Task serverTask;

Expand Down Expand Up @@ -155,3 +164,32 @@ private static async Task RunConnected(Func<IMcpClient, IMcpServer, Task> action
await serverTask;
}
}

public class LoggingStream : Stream
{
private readonly Stream _innerStream;
private readonly Action<string> _logAction;

public LoggingStream(Stream innerStream, Action<string> logAction)
{
_innerStream = innerStream ?? throw new ArgumentNullException(nameof(innerStream));
_logAction = logAction ?? throw new ArgumentNullException(nameof(logAction));
}

public override void Write(byte[] buffer, int offset, int count)
{
var data = Encoding.UTF8.GetString(buffer, offset, count);
_logAction(data);
_innerStream.Write(buffer, offset, count);
}

public override bool CanRead => _innerStream.CanRead;
public override bool CanSeek => _innerStream.CanSeek;
public override bool CanWrite => _innerStream.CanWrite;
public override long Length => _innerStream.Length;
public override long Position { get => _innerStream.Position; set => _innerStream.Position = value; }
public override void Flush() => _innerStream.Flush();
public override int Read(byte[] buffer, int offset, int count) => _innerStream.Read(buffer, offset, count);
public override long Seek(long offset, SeekOrigin origin) => _innerStream.Seek(offset, origin);
public override void SetLength(long value) => _innerStream.SetLength(value);
}