Skip to content

Commit 869a455

Browse files
committed
remove McpClient
1 parent de89187 commit 869a455

File tree

9 files changed

+180
-185
lines changed

9 files changed

+180
-185
lines changed

src/OpenAI.csproj

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,10 @@
6060
<PublicKey>0024000004800000940000000602000000240000525341310004000001000100097ad52abbeaa2e1a1982747cc0106534f65cfea6707eaed696a3a63daea80de2512746801a7e47f88e7781e71af960d89ba2e25561f70b0e2dbc93319e0af1961a719ccf5a4d28709b2b57a5d29b7c09dc8d269a490ebe2651c4b6e6738c27c5fb2c02469fe9757f0a3479ac310d6588a50a28d7dd431b907fd325e18b9e8ed</PublicKey>
6161
</InternalsVisibleTo>
6262
<InternalsVisibleTo Include="Azure.AI.OpenAI" Condition="'$(Configuration)' == 'Unsigned'" />
63+
<InternalsVisibleTo Include="OpenAI.Tests" Condition="'$(Configuration)' != 'Unsigned'">
64+
<PublicKey>0024000004800000940000000602000000240000525341310004000001000100b197326f2e5bfe2e2a49eb2a05bee871c55cc894325b3775159732ad816c4f304916e7f154295486f8ccabefa3c19b059d51cd19987cc2d31a3195d6203ad0948662f51cc61cc3eb535fc852dfe5159318c734b163f7d1387f1112e1ffe10f83aae7b809c4e36cf2025da5d1aed6b67e1556883d8778eeb63131c029555166de</PublicKey>
65+
</InternalsVisibleTo>
66+
<InternalsVisibleTo Include="OpenAI.Tests" Condition="'$(Configuration)' == 'Unsigned'" />
6367
</ItemGroup>
6468

6569
<PropertyGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">

src/Utility/ChatTools.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ internal void AddFunctionTool(MethodInfo function)
9292
/// </summary>
9393
/// <param name="client">The MCP client instance.</param>
9494
/// <returns>A task representing the asynchronous operation.</returns>
95-
public async Task AddMcpToolsAsync(McpClient client)
95+
internal async Task AddMcpToolsAsync(McpClient client)
9696
{
9797
if (client == null) throw new ArgumentNullException(nameof(client));
9898
_mcpClientsByEndpoint[client.Endpoint.AbsoluteUri] = client;

src/Utility/MCP/McpClient.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ namespace OpenAI.Agents;
88
/// Client for interacting with a Model Context Protocol (MCP) server.
99
/// </summary>
1010
//[Experimental("OPENAIMCP001")]
11-
public class McpClient
11+
internal class McpClient
1212
{
1313
private readonly McpSession _session;
1414
private readonly ClientPipeline _pipeline;

src/Utility/MCP/McpSession.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -173,8 +173,9 @@ private async Task ProcessEventAsync(SseEvent sseEvent)
173173
{
174174
var serverUri = _serverEndpoint;
175175
var endpoint = serverUri.GetLeftPart(UriPartial.Authority);
176-
string trailingSlash = endpoint.EndsWith("/") ? "" : "/";
177-
var messageEndpoint = $"{endpoint}{trailingSlash}{sseEvent.Data.Trim()}";
176+
var path = sseEvent.Data.Trim();
177+
string trailingSlash = endpoint.EndsWith("/") || path.StartsWith("/") ? "" : "/";
178+
var messageEndpoint = $"{endpoint}{trailingSlash}{path}";
178179
_endpointTcs.TrySetResult(messageEndpoint);
179180
}
180181
break;

src/Utility/ResponseTools.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ internal void AddFunctionTool(MethodInfo function)
9292
/// </summary>
9393
/// <param name="client">The MCP client instance.</param>
9494
/// <returns>A task representing the asynchronous operation.</returns>
95-
public async Task AddMcpToolsAsync(McpClient client)
95+
internal async Task AddMcpToolsAsync(McpClient client)
9696
{
9797
if (client == null) throw new ArgumentNullException(nameof(client));
9898
_mcpClientsByEndpoint[client.Endpoint.AbsoluteUri] = client;

tests/OpenAI.Tests.csproj

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,13 @@
1010

1111
<LangVersion>latest</LangVersion>
1212
</PropertyGroup>
13+
14+
<PropertyGroup Condition="'$(Configuration)' != 'Unsigned'">
15+
<!-- Sign the assembly with the specified key file. -->
16+
<SignAssembly>true</SignAssembly>
17+
<AssemblyOriginatorKeyFile>..\src\OpenAI.snk</AssemblyOriginatorKeyFile>
18+
</PropertyGroup>
19+
1320
<ItemGroup>
1421
<ProjectReference Include="..\src\OpenAI.csproj" />
1522
</ItemGroup>
@@ -22,8 +29,4 @@
2229
<PackageReference Include="System.Linq.Async" Version="6.0.1" />
2330
</ItemGroup>
2431

25-
<ItemGroup>
26-
<Compile Include="..\src\Utility\Telemetry\*.cs" LinkBase="Telemetry\Shared" />
27-
<Compile Include="..\src\Utility\AppContextSwitchHelper.cs" LinkBase="Telemetry\Shared" />
28-
</ItemGroup>
2932
</Project>

tests/Utility/ChatToolsTests.cs

Lines changed: 33 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,7 @@
11
using System;
22
using System.ClientModel;
3-
using System.ClientModel.Primitives;
43
using System.Collections.Generic;
5-
using System.IO;
64
using System.Linq;
7-
using System.Net.Http;
85
using System.Threading;
96
using System.Threading.Tasks;
107
using Moq;
@@ -17,57 +14,8 @@ namespace OpenAI.Tests.Utility;
1714

1815
[TestFixture]
1916
[Category("Utility")]
20-
public class ChatToolsTests
17+
public class ChatToolsTests : ToolsTestsBase
2118
{
22-
private class TestTools
23-
{
24-
public static string Echo(string message) => message;
25-
public static int Add(int a, int b) => a + b;
26-
public static double Multiply(double x, double y) => x * y;
27-
public static bool IsGreaterThan(long value1, long value2) => value1 > value2;
28-
public static float Divide(float numerator, float denominator) => numerator / denominator;
29-
public static string ConcatWithBool(string text, bool flag) => $"{text}:{flag}";
30-
}
31-
32-
private class TestToolsAsync
33-
{
34-
public static async Task<string> EchoAsync(string message)
35-
{
36-
await Task.Delay(1); // Simulate async work
37-
return message;
38-
}
39-
40-
public static async Task<int> AddAsync(int a, int b)
41-
{
42-
await Task.Delay(1); // Simulate async work
43-
return a + b;
44-
}
45-
46-
public static async Task<double> MultiplyAsync(double x, double y)
47-
{
48-
await Task.Delay(1); // Simulate async work
49-
return x * y;
50-
}
51-
52-
public static async Task<bool> IsGreaterThanAsync(long value1, long value2)
53-
{
54-
await Task.Delay(1); // Simulate async work
55-
return value1 > value2;
56-
}
57-
58-
public static async Task<float> DivideAsync(float numerator, float denominator)
59-
{
60-
await Task.Delay(1); // Simulate async work
61-
return numerator / denominator;
62-
}
63-
64-
public static async Task<string> ConcatWithBoolAsync(string text, bool flag)
65-
{
66-
await Task.Delay(1); // Simulate async work
67-
return $"{text}:{flag}";
68-
}
69-
}
70-
7119
private Mock<EmbeddingClient> mockEmbeddingClient;
7220

7321
[SetUp]
@@ -234,9 +182,6 @@ public async Task AddMcpToolsAsync_AddsToolsCorrectly()
234182
{
235183
// Arrange
236184
var mcpEndpoint = new Uri("http://localhost:1234");
237-
var mockMcpClient = new Mock<McpClient>(mcpEndpoint);
238-
var tools = new ChatTools();
239-
240185
var mockToolsResponse = BinaryData.FromString(@"
241186
{
242187
""tools"": [
@@ -279,42 +224,48 @@ public async Task AddMcpToolsAsync_AddsToolsCorrectly()
279224
]
280225
}");
281226

282-
mockMcpClient.Setup(c => c.StartAsync())
283-
.Returns(Task.CompletedTask);
284-
mockMcpClient.Setup(c => c.ListToolsAsync())
285-
.ReturnsAsync(mockToolsResponse);
286-
mockMcpClient.Setup(c => c.CallToolAsync(It.IsAny<string>(), It.IsAny<BinaryData>()))
287-
.ReturnsAsync(BinaryData.FromString("\"test result\""));
288-
mockMcpClient.SetupGet(c => c.Endpoint)
289-
.Returns(mcpEndpoint);
227+
var responsesByTool = new Dictionary<string, string>
228+
{
229+
["mcp-tool-1"] = "\"tool1 result\"",
230+
["mcp-tool-2"] = "\"tool2 result\""
231+
};
232+
233+
var testClient = new TestMcpClient(
234+
mcpEndpoint,
235+
mockToolsResponse,
236+
toolName => BinaryData.FromString(responsesByTool[toolName.Split('_').Last()]));
237+
var tools = new ChatTools();
290238

291239
// Act
292-
await tools.AddMcpToolsAsync(mockMcpClient.Object);
240+
await tools.AddMcpToolsAsync(testClient);
293241

294242
// Assert
295243
Assert.That(tools.Tools, Has.Count.EqualTo(2));
296244
var toolNames = tools.Tools.Select(t => t.FunctionName).ToList();
297245
Assert.That(toolNames, Contains.Item("localhost1234_-_mcp-tool-1"));
298246
Assert.That(toolNames, Contains.Item("localhost1234_-_mcp-tool-2"));
299247

300-
// Verify we can call the tools
301-
var toolCall = ChatToolCall.CreateFunctionToolCall("call1", "localhost1234_-_mcp-tool-1", BinaryData.FromString(@"{""param1"": ""test""}"));
302-
var result = await tools.CallAsync(new[] { toolCall });
303-
var resultsList = result.ToList();
248+
// Verify we can call the tools with different responses
249+
var toolCalls = new[]
250+
{
251+
ChatToolCall.CreateFunctionToolCall("call1", "localhost1234_-_mcp-tool-1", BinaryData.FromString(@"{""param1"": ""test""}")),
252+
ChatToolCall.CreateFunctionToolCall("call2", "localhost1234_-_mcp-tool-2", BinaryData.FromString(@"{""param2"": ""test""}"))
253+
};
254+
var results = await tools.CallAsync(toolCalls);
255+
var resultsList = results.ToList();
304256

305-
Assert.That(resultsList, Has.Count.EqualTo(1));
257+
Assert.That(resultsList, Has.Count.EqualTo(2));
306258
Assert.That(resultsList[0].ToolCallId, Is.EqualTo("call1"));
307-
Assert.That(resultsList[0].Content[0].Text, Is.EqualTo("\"test result\""));
259+
Assert.That(resultsList[0].Content[0].Text, Is.EqualTo("\"tool1 result\""));
260+
Assert.That(resultsList[1].ToolCallId, Is.EqualTo("call2"));
261+
Assert.That(resultsList[1].Content[0].Text, Is.EqualTo("\"tool2 result\""));
308262
}
309263

310264
[Test]
311265
public async Task CreateCompletionOptions_WithMaxToolsParameter_FiltersTools()
312266
{
313267
// Arrange
314268
var mcpEndpoint = new Uri("http://localhost:1234");
315-
var mockMcpClient = new Mock<McpClient>(mcpEndpoint);
316-
var tools = new ChatTools(mockEmbeddingClient.Object);
317-
318269
var mockToolsResponse = BinaryData.FromString(@"
319270
{
320271
""tools"": [
@@ -364,7 +315,7 @@ public async Task CreateCompletionOptions_WithMaxToolsParameter_FiltersTools()
364315
]
365316
}");
366317

367-
// Setup mock responses
318+
// Setup mock embedding responses
368319
var embeddings = new[]
369320
{
370321
OpenAIEmbeddingsModelFactory.OpenAIEmbedding(vector: new[] { 0.8f, 0.5f }),
@@ -377,15 +328,6 @@ public async Task CreateCompletionOptions_WithMaxToolsParameter_FiltersTools()
377328
usage: OpenAIEmbeddingsModelFactory.EmbeddingTokenUsage(30, 30));
378329
var mockResponse = new MockPipelineResponse(200);
379330

380-
mockMcpClient.Setup(c => c.StartAsync())
381-
.Returns(Task.CompletedTask);
382-
mockMcpClient.Setup(c => c.ListToolsAsync())
383-
.ReturnsAsync(mockToolsResponse);
384-
mockMcpClient.Setup(c => c.CallToolAsync("math-tool", It.IsAny<BinaryData>()))
385-
.ReturnsAsync(BinaryData.FromString("\"math-tool result\""));
386-
mockMcpClient.SetupGet(c => c.Endpoint)
387-
.Returns(mcpEndpoint);
388-
389331
mockEmbeddingClient
390332
.Setup(c => c.GenerateEmbeddingAsync(
391333
It.IsAny<string>(),
@@ -400,8 +342,14 @@ public async Task CreateCompletionOptions_WithMaxToolsParameter_FiltersTools()
400342
It.IsAny<CancellationToken>()))
401343
.ReturnsAsync(ClientResult.FromValue(embeddingCollection, mockResponse));
402344

345+
var testClient = new TestMcpClient(
346+
mcpEndpoint,
347+
mockToolsResponse,
348+
toolName => BinaryData.FromString($"\"{toolName} result\""));
349+
var tools = new ChatTools(mockEmbeddingClient.Object);
350+
403351
// Add the tools
404-
await tools.AddMcpToolsAsync(mockMcpClient.Object);
352+
await tools.AddMcpToolsAsync(testClient);
405353

406354
// Act & Assert
407355
// Test with maxTools = 1
@@ -420,9 +368,5 @@ public async Task CreateCompletionOptions_WithMaxToolsParameter_FiltersTools()
420368
var result = await tools.CallAsync(new[] { toolCall });
421369
Assert.That(result.First().ToolCallId, Is.EqualTo("call1"));
422370
Assert.That(result.First().Content[0].Text, Is.EqualTo("\"math-tool result\""));
423-
424-
// Verify expected interactions
425-
mockMcpClient.Verify(c => c.StartAsync(), Times.Once);
426-
mockMcpClient.Verify(c => c.ListToolsAsync(), Times.Once);
427371
}
428372
}

0 commit comments

Comments
 (0)