|
4 | 4 | #:package ModelContextProtocol.Core@*-* |
5 | 5 | #:property PublishAot=false |
6 | 6 |
|
| 7 | +using System.Text.Json; |
| 8 | +using ModelContextProtocol; |
7 | 9 | using ModelContextProtocol.Client; |
8 | 10 | using OpenAI.Chat; |
9 | 11 |
|
|
45 | 47 | Console.WriteLine("Tool call detected, calling MCP server..."); |
46 | 48 | ModelContextProtocol.Protocol.CallToolResult result = await mcpClient.CallToolAsync(call.FunctionName, mcpArguments!); |
47 | 49 | Console.WriteLine($"tool call result {result.Content[0]}"); |
48 | | - ChatMessage message = result.ToMessage(call); |
| 50 | + ChatMessage message = call.ToMessage(result.Content.ToAIContents()); |
49 | 51 | conversation.Add(message); |
50 | 52 | } |
51 | 53 | goto start; |
|
60 | 62 | // this is temporary. all these APIs will endup being in one of the packages used here. |
61 | 63 | public static class TemporaryExtensions |
62 | 64 | { |
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) |
64 | 67 | { |
65 | 68 | 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) |
69 | 70 | { |
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)); |
78 | 76 | } |
79 | 77 | ToolChatMessage message = ChatMessage.CreateToolMessage(openaiCall.Id, parts); |
80 | 78 | return message; |
81 | 79 | } |
82 | 80 |
|
83 | | - // this is in the adapter package; waiting for package to be dropped. |
| 81 | + // this is in the adapter package |
84 | 82 | public static ChatTool AsOpenAIChatTool(this Microsoft.Extensions.AI.AIFunction mcpTool) |
85 | 83 | { |
86 | 84 | return ChatTool.CreateFunctionTool( |
|
0 commit comments