Skip to content

Commit 422fb5d

Browse files
simplified dependencies of ToMessage
1 parent abacb03 commit 422fb5d

File tree

1 file changed

+12
-14
lines changed

1 file changed

+12
-14
lines changed

docs/guides/mcp/chat_with_mcp.cs

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
#:package ModelContextProtocol.Core@*-*
55
#:property PublishAot=false
66

7+
using System.Text.Json;
8+
using ModelContextProtocol;
79
using ModelContextProtocol.Client;
810
using OpenAI.Chat;
911

@@ -45,7 +47,7 @@
4547
Console.WriteLine("Tool call detected, calling MCP server...");
4648
ModelContextProtocol.Protocol.CallToolResult result = await mcpClient.CallToolAsync(call.FunctionName, mcpArguments!);
4749
Console.WriteLine($"tool call result {result.Content[0]}");
48-
ChatMessage message = result.ToMessage(call);
50+
ChatMessage message = call.ToMessage(result.Content.ToAIContents());
4951
conversation.Add(message);
5052
}
5153
goto start;
@@ -60,27 +62,23 @@
6062
// this is temporary. all these APIs will endup being in one of the packages used here.
6163
public static class TemporaryExtensions
6264
{
63-
public static ChatMessage ToMessage(this ModelContextProtocol.Protocol.CallToolResult mcpCallResult, ChatToolCall openaiCall)
65+
// this needs to be in the adapter package
66+
public static ChatMessage ToMessage(this ChatToolCall openaiCall, IEnumerable<Microsoft.Extensions.AI.AIContent> contents)
6467
{
6568
List<ChatMessageContentPart> parts = new();
66-
var sc = mcpCallResult.StructuredContent;
67-
68-
foreach (ModelContextProtocol.Protocol.ContentBlock block in mcpCallResult.Content)
69+
foreach (Microsoft.Extensions.AI.AIContent content in contents)
6970
{
70-
if (block is ModelContextProtocol.Protocol.TextContentBlock textContent)
71-
{
72-
parts.Add(ChatMessageContentPart.CreateTextPart(textContent.Text));
73-
}
74-
else
75-
{
76-
throw new NotImplementedException();
77-
}
71+
string serialized = JsonSerializer.Serialize(content.RawRepresentation);
72+
using JsonDocument json = JsonDocument.Parse(serialized);
73+
JsonElement text = json.RootElement.GetProperty("text");
74+
string textValue = text.GetString() ?? string.Empty;
75+
parts.Add(ChatMessageContentPart.CreateTextPart(textValue));
7876
}
7977
ToolChatMessage message = ChatMessage.CreateToolMessage(openaiCall.Id, parts);
8078
return message;
8179
}
8280

83-
// this is in the adapter package; waiting for package to be dropped.
81+
// this is in the adapter package
8482
public static ChatTool AsOpenAIChatTool(this Microsoft.Extensions.AI.AIFunction mcpTool)
8583
{
8684
return ChatTool.CreateFunctionTool(

0 commit comments

Comments
 (0)