openai/openai-dotnet

Public

mirrored from https://github.com/openai/openai-dotnetAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
jsquire-patch-1

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

src/Utility/MCP/McpClient.cs

68lines · modecode

1using System;
2using System.ClientModel.Primitives;
3using System.Threading.Tasks;
4
5namespace OpenAI.Agents;
6
7/// <summary>
8/// Client for interacting with a Model Context Protocol (MCP) server.
9/// </summary>
10//[Experimental("OPENAIMCP001")]
11internal class McpClient
12{
13 private readonly McpSession _session;
14 private readonly ClientPipeline _pipeline;
15
16 /// <summary>
17 /// Gets the endpoint URI of the MCP server.
18 /// </summary>
19 public virtual Uri Endpoint { get; }
20
21 /// <summary>
22 /// Initializes a new instance of the <see cref="McpClient"/> class.
23 /// </summary>
24 /// <param name="endpoint">The URI endpoint of the MCP server.</param>
25 public McpClient(Uri endpoint)
26 {
27 _pipeline = ClientPipeline.Create();
28 _session = new McpSession(endpoint, _pipeline);
29 Endpoint = endpoint;
30 }
31
32 /// <summary>
33 /// Starts the MCP client session by initializing the connection to the server.
34 /// </summary>
35 /// <returns>A task that represents the asynchronous operation.</returns>
36 public virtual async Task StartAsync()
37 {
38 await _session.EnsureInitializedAsync().ConfigureAwait(false);
39 }
40
41 /// <summary>
42 /// Lists all available tools from the MCP server.
43 /// </summary>
44 /// <returns>A task that represents the asynchronous operation. The task result contains the binary data representing the tools list.</returns>
45 /// <exception cref="InvalidOperationException">Thrown when the session is not initialized.</exception>
46 public virtual async Task<BinaryData> ListToolsAsync()
47 {
48 if (_session == null)
49 throw new InvalidOperationException("Session is not initialized. Call StartAsync() first.");
50
51 return await _session.SendMethod("tools/list").ConfigureAwait(false);
52 }
53
54 /// <summary>
55 /// Calls a specific tool on the MCP server.
56 /// </summary>
57 /// <param name="toolName">The name of the tool to call.</param>
58 /// <param name="parameters">The parameters to pass to the tool as binary data.</param>
59 /// <returns>A task that represents the asynchronous operation. The task result contains the binary data representing the tool's response.</returns>
60 /// <exception cref="InvalidOperationException">Thrown when the session is not initialized.</exception>
61 public virtual async Task<BinaryData> CallToolAsync(string toolName, BinaryData parameters)
62 {
63 if (_session == null)
64 throw new InvalidOperationException("Session is not initialized. Call StartAsync() first.");
65
66 return await _session.CallTool(toolName, parameters).ConfigureAwait(false);
67 }
68}
69