Server support (stdio) (#19)
* Server support (stdio) * TestServer project * Refactored McpClient class to extract shared endpoint logic (with McpServer) to a base class, McpJsonRpcEndpoint. * Improved xmldoc comments for protocol types, mirroring specification schema comments. * Update README.MD
This commit is contained in:
parent
c384c7d3de
commit
8fe797e1f3
8 changed files with 2668 additions and 659 deletions
50
tests/mcpdotnet.Tests/ClientIntegrationTestFixture.cs
Normal file
50
tests/mcpdotnet.Tests/ClientIntegrationTestFixture.cs
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
using McpDotNet.Client;
|
||||
using McpDotNet.Configuration;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace McpDotNet.Tests;
|
||||
|
||||
public class ClientIntegrationTestFixture : IDisposable
|
||||
{
|
||||
public ILoggerFactory LoggerFactory { get; }
|
||||
public McpClientFactory Factory { get; }
|
||||
public McpClientOptions DefaultOptions { get; }
|
||||
public McpServerConfig DefaultConfig { get; }
|
||||
|
||||
public ClientIntegrationTestFixture()
|
||||
{
|
||||
LoggerFactory = Microsoft.Extensions.Logging.LoggerFactory.Create(builder =>
|
||||
builder.AddConsole()
|
||||
.SetMinimumLevel(LogLevel.Debug));
|
||||
|
||||
DefaultOptions = new()
|
||||
{
|
||||
ClientInfo = new() { Name = "IntegrationTestClient", Version = "1.0.0" }
|
||||
};
|
||||
|
||||
DefaultConfig = new McpServerConfig
|
||||
{
|
||||
Id = "everything",
|
||||
Name = "Everything",
|
||||
TransportType = "stdio",
|
||||
TransportOptions = new Dictionary<string, string>
|
||||
{
|
||||
["command"] = "npx",
|
||||
// Change to ["arguments"] = "mcp-server-everything" if you want to run the server locally after creating a symlink
|
||||
["arguments"] = "-y @modelcontextprotocol/server-everything",
|
||||
}
|
||||
};
|
||||
|
||||
// Inject the mock transport into the factory
|
||||
Factory = new McpClientFactory(
|
||||
[DefaultConfig],
|
||||
DefaultOptions,
|
||||
LoggerFactory
|
||||
);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
LoggerFactory?.Dispose();
|
||||
}
|
||||
}
|
||||
461
tests/mcpdotnet.Tests/ClientIntegrationTests.cs
Normal file
461
tests/mcpdotnet.Tests/ClientIntegrationTests.cs
Normal file
|
|
@ -0,0 +1,461 @@
|
|||
using McpDotNet.Client;
|
||||
using McpDotNet.Configuration;
|
||||
using McpDotNet.Protocol.Messages;
|
||||
using McpDotNet.Protocol.Types;
|
||||
|
||||
namespace McpDotNet.Tests;
|
||||
|
||||
public class ClientIntegrationTests : IClassFixture<ClientIntegrationTestFixture>
|
||||
{
|
||||
private readonly ClientIntegrationTestFixture _fixture;
|
||||
|
||||
public ClientIntegrationTests(ClientIntegrationTestFixture fixture)
|
||||
{
|
||||
_fixture = fixture;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConnectAndPing_Stdio_EverythingServer()
|
||||
{
|
||||
// Arrange
|
||||
|
||||
// Act
|
||||
var client = await _fixture.Factory.GetClientAsync("everything");
|
||||
await client.PingAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(client);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Connect_EverythingServer_ShouldProvideServerFields()
|
||||
{
|
||||
// Arrange
|
||||
|
||||
// Act
|
||||
var client = await _fixture.Factory.GetClientAsync("everything");
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(client.ServerCapabilities);
|
||||
Assert.NotNull(client.ServerInfo);
|
||||
|
||||
// Note: Comment the below assertion back when the everything server is updated to provide instructions
|
||||
// Assert.NotNull(client.ServerInstructions);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ListTools_Stdio_EverythingServer()
|
||||
{
|
||||
// arrange
|
||||
|
||||
// act
|
||||
var client = await _fixture.Factory.GetClientAsync("everything");
|
||||
var tools = await client.ListToolsAsync();
|
||||
|
||||
// assert
|
||||
Assert.NotNull(tools);
|
||||
Assert.NotEmpty(tools.Tools);
|
||||
// We could add more specific assertions about expected tools
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CallTool_Stdio_EchoServer()
|
||||
{
|
||||
// arrange
|
||||
|
||||
// act
|
||||
var client = await _fixture.Factory.GetClientAsync("everything");
|
||||
var result = await client.CallToolAsync(
|
||||
"echo",
|
||||
new Dictionary<string, object>
|
||||
{
|
||||
["message"] = "Hello MCP!"
|
||||
},
|
||||
CancellationToken.None
|
||||
);
|
||||
|
||||
// assert
|
||||
Assert.NotNull(result);
|
||||
Assert.False(result.IsError);
|
||||
var textContent = Assert.Single(result.Content, c => c.Type == "text");
|
||||
Assert.Equal("Echo: Hello MCP!", textContent.Text);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ListPrompts_Stdio_EverythingServer()
|
||||
{
|
||||
// arrange
|
||||
|
||||
// act
|
||||
var client = await _fixture.Factory.GetClientAsync("everything");
|
||||
var prompts = await client.ListPromptsAsync();
|
||||
|
||||
// assert
|
||||
Assert.NotNull(prompts);
|
||||
Assert.NotEmpty(prompts.Prompts);
|
||||
// We could add specific assertions for the known prompts
|
||||
Assert.Contains(prompts.Prompts, p => p.Name == "simple_prompt");
|
||||
Assert.Contains(prompts.Prompts, p => p.Name == "complex_prompt");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPrompt_Stdio_SimplePrompt()
|
||||
{
|
||||
// arrange
|
||||
|
||||
// act
|
||||
var client = await _fixture.Factory.GetClientAsync("everything");
|
||||
var result = await client.GetPromptAsync("simple_prompt", null, CancellationToken.None);
|
||||
|
||||
// assert
|
||||
Assert.NotNull(result);
|
||||
Assert.NotEmpty(result.Messages);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPrompt_Stdio_ComplexPrompt()
|
||||
{
|
||||
// arrange
|
||||
|
||||
// act
|
||||
var client = await _fixture.Factory.GetClientAsync("everything");
|
||||
var arguments = new Dictionary<string, object>
|
||||
{
|
||||
{ "temperature", "0.7" },
|
||||
{ "style", "formal" }
|
||||
};
|
||||
var result = await client.GetPromptAsync("complex_prompt", arguments, CancellationToken.None);
|
||||
|
||||
// assert
|
||||
Assert.NotNull(result);
|
||||
Assert.NotEmpty(result.Messages);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPrompt_NonExistent_ThrowsException()
|
||||
{
|
||||
// arrange
|
||||
|
||||
// act
|
||||
var client = await _fixture.Factory.GetClientAsync("everything");
|
||||
await Assert.ThrowsAsync<McpClientException>(() =>
|
||||
client.GetPromptAsync("non_existent_prompt", null, CancellationToken.None));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ListResources_Stdio_EverythingServer()
|
||||
{
|
||||
// arrange
|
||||
|
||||
// act
|
||||
var client = await _fixture.Factory.GetClientAsync("everything");
|
||||
|
||||
List<Resource> allResources = new();
|
||||
string? cursor = null;
|
||||
do
|
||||
{
|
||||
var resources = await client.ListResourcesAsync(cursor, CancellationToken.None);
|
||||
allResources.AddRange(resources.Resources);
|
||||
cursor = resources.NextCursor;
|
||||
}
|
||||
while (cursor != null);
|
||||
|
||||
// The everything server provides 100 test resources
|
||||
Assert.Equal(100, allResources.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReadResource_Stdio_TextResource()
|
||||
{
|
||||
// arrange
|
||||
|
||||
// act
|
||||
var client = await _fixture.Factory.GetClientAsync("everything");
|
||||
// Odd numbered resources are text in the everything server (despite the docs saying otherwise)
|
||||
// 1 is index 0, which is "even" in the 0-based index
|
||||
var result = await client.ReadResourceAsync("test://static/resource/1", CancellationToken.None);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Single(result.Contents);
|
||||
Assert.NotNull(result.Contents[0].Text);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReadResource_Stdio_BinaryResource()
|
||||
{
|
||||
// arrange
|
||||
|
||||
// act
|
||||
var client = await _fixture.Factory.GetClientAsync("everything");
|
||||
// Even numbered resources are binary in the everything server (despite the docs saying otherwise)
|
||||
// 2 is index 1, which is "odd" in the 0-based index
|
||||
var result = await client.ReadResourceAsync("test://static/resource/2", CancellationToken.None);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Single(result.Contents);
|
||||
Assert.NotNull(result.Contents[0].Blob);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Note that as of 19th January 2025, the everything server published to npx does not support prompt completion.
|
||||
/// However, the prompt completion is implemented in the github.com/modelcontextprotocol/servers repository.
|
||||
/// You can clone this repo, and build locally then change the config to use a local symlink instead of npx until this is fixed, if you wish to run this test.
|
||||
/// TransportOptions = new Dictionary<string, string>
|
||||
/// {
|
||||
/// ["command"] = "npx",
|
||||
/// ["arguments"] = "mcp-server-everything" // changed from "-y @modelcontextprotocol/server-everything"
|
||||
/// }
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task GetCompletion_Stdio_ResourceReference()
|
||||
{
|
||||
// arrange
|
||||
|
||||
// act
|
||||
var client = await _fixture.Factory.GetClientAsync("everything");
|
||||
var result = await client.GetCompletionAsync(new Reference
|
||||
{
|
||||
Type = "ref/resource",
|
||||
Uri = "test://static/resource/1"
|
||||
},
|
||||
"argument_name", "1",
|
||||
CancellationToken.None
|
||||
);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Single(result.Completion.Values);
|
||||
Assert.True(result.Completion.Values[0] == "1");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Note that as of 19th January 2025, the everything server published to npx does not support prompt completion.
|
||||
/// However, the prompt completion is implemented in the github.com/modelcontextprotocol/servers repository.
|
||||
/// You can clone this repo, and build locally then change the config to use a local symlink instead of npx until this is fixed, if you wish to run this test.
|
||||
/// TransportOptions = new Dictionary<string, string>
|
||||
/// {
|
||||
/// ["command"] = "npx",
|
||||
/// ["arguments"] = "mcp-server-everything" // changed from "-y @modelcontextprotocol/server-everything"
|
||||
/// }
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task GetCompletion_Stdio_PromptReference()
|
||||
{
|
||||
// arrange
|
||||
|
||||
// act
|
||||
var client = await _fixture.Factory.GetClientAsync("everything");
|
||||
var result = await client.GetCompletionAsync(new Reference
|
||||
{
|
||||
Type = "ref/prompt",
|
||||
Name = "irrelevant"
|
||||
},
|
||||
argumentName:"style", argumentValue:"fo",
|
||||
CancellationToken.None
|
||||
);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Single(result.Completion.Values);
|
||||
Assert.True(result.Completion.Values[0] == "formal");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Sampling_Stdio_EverythingServer()
|
||||
{
|
||||
// arrange
|
||||
var config = new McpServerConfig
|
||||
{
|
||||
Id = "everything",
|
||||
Name = "Everything",
|
||||
TransportType = "stdio",
|
||||
TransportOptions = new Dictionary<string, string>
|
||||
{
|
||||
["command"] = "npx",
|
||||
["arguments"] = "-y @modelcontextprotocol/server-everything",
|
||||
}
|
||||
};
|
||||
|
||||
var options = new McpClientOptions
|
||||
{
|
||||
ClientInfo = new() { Name = "IntegrationTestClient", Version = "1.0.0" },
|
||||
Capabilities = new ClientCapabilities
|
||||
{
|
||||
Sampling = new()
|
||||
}
|
||||
};
|
||||
|
||||
var factory = new McpClientFactory(
|
||||
[config],
|
||||
options,
|
||||
_fixture.LoggerFactory
|
||||
);
|
||||
var client = await factory.GetClientAsync("everything");
|
||||
|
||||
// Set up the sampling handler
|
||||
int samplingHandlerCalls = 0;
|
||||
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
|
||||
client.SamplingHandler = async (_,_) =>
|
||||
{
|
||||
samplingHandlerCalls++;
|
||||
return new CreateMessageResult
|
||||
{
|
||||
Model = "test-model",
|
||||
Role = "assistant",
|
||||
Content = new Content
|
||||
{
|
||||
Type = "text",
|
||||
Text = "Test response"
|
||||
}
|
||||
};
|
||||
};
|
||||
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
|
||||
|
||||
// Call the server's sampleLLM tool which should trigger our sampling handler
|
||||
var result = await client.CallToolAsync(
|
||||
"sampleLLM",
|
||||
new Dictionary<string, object>
|
||||
{
|
||||
["prompt"] = "Test prompt",
|
||||
["maxTokens"] = 100
|
||||
}
|
||||
);
|
||||
|
||||
// assert
|
||||
Assert.NotNull(result);
|
||||
var textContent = Assert.Single(result.Content);
|
||||
Assert.Equal("text", textContent.Type);
|
||||
Assert.False(string.IsNullOrEmpty(textContent.Text));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Roots_Stdio_EverythingServer()
|
||||
{
|
||||
// arrange
|
||||
var config = new McpServerConfig
|
||||
{
|
||||
Id = "everything",
|
||||
Name = "everything",
|
||||
TransportType = "stdio",
|
||||
TransportOptions = new Dictionary<string, string>
|
||||
{
|
||||
["command"] = "npx",
|
||||
["arguments"] = "-y @modelcontextprotocol/server-everything"
|
||||
}
|
||||
};
|
||||
|
||||
var options = new McpClientOptions
|
||||
{
|
||||
ClientInfo = new() { Name = "IntegrationTestClient", Version = "1.0.0" },
|
||||
Capabilities = new ClientCapabilities
|
||||
{
|
||||
Roots = new()
|
||||
}
|
||||
};
|
||||
|
||||
var rootsHandlerCalls = 0;
|
||||
var testRoots = new List<Root>
|
||||
{
|
||||
new() { Uri = "file:///test/root1", Name = "Test Root 1" },
|
||||
new() { Uri = "file:///test/root2", Name = "Test Root 2" }
|
||||
};
|
||||
|
||||
var factory = new McpClientFactory(
|
||||
[config],
|
||||
options,
|
||||
_fixture.LoggerFactory
|
||||
);
|
||||
var client = await factory.GetClientAsync("everything");
|
||||
|
||||
// Set up the roots handler
|
||||
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
|
||||
client.RootsHandler = async (request, ct) =>
|
||||
{
|
||||
rootsHandlerCalls++;
|
||||
return new ListRootsResult
|
||||
{
|
||||
Roots = testRoots
|
||||
};
|
||||
};
|
||||
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
|
||||
|
||||
// Connect
|
||||
await client.ConnectAsync(CancellationToken.None);
|
||||
|
||||
// assert
|
||||
// nothing to assert, no servers implement roots, so we if no exception is thrown, it's a success
|
||||
Assert.True(true);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Notifications_Stdio_EverythingServer()
|
||||
{
|
||||
// arrange
|
||||
var config = new McpServerConfig
|
||||
{
|
||||
Id = "everything",
|
||||
Name = "everything",
|
||||
TransportType = "stdio",
|
||||
TransportOptions = new Dictionary<string, string>
|
||||
{
|
||||
["command"] = "npx",
|
||||
["arguments"] = "-y @modelcontextprotocol/server-everything"
|
||||
}
|
||||
};
|
||||
|
||||
var options = new McpClientOptions
|
||||
{
|
||||
ClientInfo = new() { Name = "IntegrationTestClient", Version = "1.0.0" }
|
||||
};
|
||||
|
||||
var factory = new McpClientFactory([config], options, _fixture.LoggerFactory);
|
||||
var client = await factory.GetClientAsync("everything");
|
||||
|
||||
await client.ConnectAsync();
|
||||
|
||||
// Verify we can send notifications without errors
|
||||
await client.SendNotificationAsync(NotificationMethods.RootsUpdatedNotification);
|
||||
await client.SendNotificationAsync("test/notification", new { test = true });
|
||||
|
||||
// assert
|
||||
// no response to check, if no exception is thrown, it's a success
|
||||
Assert.True(true);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CallTool_Stdio_MemoryServer()
|
||||
{
|
||||
// arrange
|
||||
var config = new McpServerConfig
|
||||
{
|
||||
Id = "memory",
|
||||
Name = "memory",
|
||||
TransportType = "stdio",
|
||||
TransportOptions = new Dictionary<string, string>
|
||||
{
|
||||
["command"] = "npx",
|
||||
["arguments"] = "-y @modelcontextprotocol/server-memory"
|
||||
}
|
||||
};
|
||||
|
||||
var options = new McpClientOptions
|
||||
{
|
||||
ClientInfo = new() { Name = "IntegrationTestClient", Version = "1.0.0" }
|
||||
};
|
||||
|
||||
var factory = new McpClientFactory([config], options, _fixture.LoggerFactory);
|
||||
var client = await factory.GetClientAsync("memory");
|
||||
|
||||
await client.ConnectAsync();
|
||||
|
||||
// act
|
||||
var result = await client.CallToolAsync(
|
||||
"read_graph",
|
||||
new Dictionary<string, object>(),
|
||||
CancellationToken.None
|
||||
);
|
||||
|
||||
// assert
|
||||
Assert.NotNull(result);
|
||||
Assert.False(result.IsError);
|
||||
var textContent = Assert.Single(result.Content, c => c.Type == "text");
|
||||
}
|
||||
}
|
||||
|
|
@ -33,7 +33,7 @@ public class McpClientFactoryTests
|
|||
};
|
||||
|
||||
// Create a mock transport
|
||||
var mockTransport = new Mock<IMcpTransport>();
|
||||
var mockTransport = new Mock<IClientTransport>();
|
||||
mockTransport.Setup(t => t.ConnectAsync(It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
mockTransport.Setup(t => t.IsConnected).Returns(true);
|
||||
|
|
@ -75,7 +75,7 @@ public class McpClientFactoryTests
|
|||
};
|
||||
|
||||
// Create a mock transport
|
||||
var mockTransport = new Mock<IMcpTransport>();
|
||||
var mockTransport = new Mock<IClientTransport>();
|
||||
mockTransport.Setup(t => t.ConnectAsync(It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
mockTransport.Setup(t => t.IsConnected).Returns(true);
|
||||
|
|
@ -149,7 +149,7 @@ public class McpClientFactoryTests
|
|||
};
|
||||
|
||||
// Create a mock transport
|
||||
var mockTransport = new Mock<IMcpTransport>();
|
||||
var mockTransport = new Mock<IClientTransport>();
|
||||
mockTransport.Setup(t => t.ConnectAsync(It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
mockTransport.Setup(t => t.IsConnected).Returns(true);
|
||||
|
|
@ -202,7 +202,7 @@ public class McpClientFactoryTests
|
|||
};
|
||||
|
||||
// Create a mock transport
|
||||
var mockTransport = new Mock<IMcpTransport>();
|
||||
var mockTransport = new Mock<IClientTransport>();
|
||||
mockTransport.Setup(t => t.ConnectAsync(It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
mockTransport.Setup(t => t.IsConnected).Returns(true);
|
||||
|
|
@ -256,7 +256,7 @@ public class McpClientFactoryTests
|
|||
NullLoggerFactory.Instance
|
||||
);
|
||||
|
||||
var transport = factory.TransportFactoryMethod(config) as SseTransport;
|
||||
var transport = factory.TransportFactoryMethod(config) as SseClientTransport;
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(transport);
|
||||
|
|
@ -278,7 +278,7 @@ public class McpClientFactoryTests
|
|||
Location = "http://localhost:8080"
|
||||
};
|
||||
|
||||
var defaultOptions = new SseTransportOptions();
|
||||
var defaultOptions = new SseClientTransportOptions();
|
||||
|
||||
// Act
|
||||
var factory = new McpClientFactory(
|
||||
|
|
@ -287,7 +287,7 @@ public class McpClientFactoryTests
|
|||
NullLoggerFactory.Instance
|
||||
);
|
||||
|
||||
var transport = factory.TransportFactoryMethod(config) as SseTransport;
|
||||
var transport = factory.TransportFactoryMethod(config) as SseClientTransport;
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(transport);
|
||||
|
|
@ -314,7 +314,7 @@ public class McpClientFactoryTests
|
|||
}
|
||||
};
|
||||
|
||||
var defaultOptions = new SseTransportOptions();
|
||||
var defaultOptions = new SseClientTransportOptions();
|
||||
|
||||
// Act
|
||||
var factory = new McpClientFactory(
|
||||
|
|
@ -323,7 +323,7 @@ public class McpClientFactoryTests
|
|||
NullLoggerFactory.Instance
|
||||
);
|
||||
|
||||
var transport = factory.TransportFactoryMethod(config) as SseTransport;
|
||||
var transport = factory.TransportFactoryMethod(config) as SseClientTransport;
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(transport);
|
||||
|
|
|
|||
53
tests/mcpdotnet.Tests/ServerIntegrationTestFixture.cs
Normal file
53
tests/mcpdotnet.Tests/ServerIntegrationTestFixture.cs
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
using McpDotNet.Client;
|
||||
using McpDotNet.Configuration;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace McpDotNet.Tests;
|
||||
|
||||
public class ServerIntegrationTestFixture : IDisposable
|
||||
{
|
||||
public ILoggerFactory LoggerFactory { get; }
|
||||
public McpClientFactory Factory { get; }
|
||||
public McpClientOptions DefaultOptions { get; }
|
||||
public McpServerConfig DefaultConfig { get; }
|
||||
|
||||
public ServerIntegrationTestFixture()
|
||||
{
|
||||
LoggerFactory = Microsoft.Extensions.Logging.LoggerFactory.Create(builder =>
|
||||
builder.AddConsole()
|
||||
.SetMinimumLevel(LogLevel.Debug));
|
||||
|
||||
DefaultOptions = new()
|
||||
{
|
||||
ClientInfo = new() { Name = "IntegrationTestClient", Version = "1.0.0" },
|
||||
Capabilities = new() { Sampling = new(), Roots = new() }
|
||||
};
|
||||
|
||||
DefaultConfig = new McpServerConfig
|
||||
{
|
||||
Id = "test_server",
|
||||
Name = "TestServer",
|
||||
TransportType = "stdio",
|
||||
TransportOptions = new Dictionary<string, string>
|
||||
{
|
||||
["command"] = "TestServer.exe",
|
||||
// Change to ["arguments"] = "mcp-server-everything" if you want to run the server locally after creating a symlink
|
||||
}
|
||||
};
|
||||
|
||||
// Inject the mock transport into the factory
|
||||
Factory = new McpClientFactory(
|
||||
[DefaultConfig],
|
||||
DefaultOptions,
|
||||
LoggerFactory
|
||||
);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
var client = Factory.GetClientAsync("test_server").Result;
|
||||
client.DisposeAsync().AsTask().Wait();
|
||||
LoggerFactory?.Dispose();
|
||||
}
|
||||
}
|
||||
239
tests/mcpdotnet.Tests/ServerIntegrationTests.cs
Normal file
239
tests/mcpdotnet.Tests/ServerIntegrationTests.cs
Normal file
|
|
@ -0,0 +1,239 @@
|
|||
using McpDotNet.Client;
|
||||
using McpDotNet.Configuration;
|
||||
using McpDotNet.Protocol.Messages;
|
||||
using McpDotNet.Protocol.Types;
|
||||
|
||||
namespace McpDotNet.Tests;
|
||||
|
||||
public class ServerIntegrationTests : IClassFixture<ServerIntegrationTestFixture>
|
||||
{
|
||||
private readonly ServerIntegrationTestFixture _fixture;
|
||||
|
||||
public ServerIntegrationTests(ServerIntegrationTestFixture fixture)
|
||||
{
|
||||
_fixture = fixture;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConnectAndPing_Stdio_TestServer()
|
||||
{
|
||||
// Arrange
|
||||
|
||||
// Act
|
||||
var client = await _fixture.Factory.GetClientAsync("test_server");
|
||||
await client.PingAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(client);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Connect_TestServer_ShouldProvideServerFields()
|
||||
{
|
||||
// Arrange
|
||||
|
||||
// Act
|
||||
var client = await _fixture.Factory.GetClientAsync("test_server");
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(client.ServerCapabilities);
|
||||
Assert.NotNull(client.ServerInfo);
|
||||
Assert.NotNull(client.ServerInstructions);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ListTools_Stdio_TestServer()
|
||||
{
|
||||
// arrange
|
||||
|
||||
// act
|
||||
var client = await _fixture.Factory.GetClientAsync("test_server");
|
||||
var tools = await client.ListToolsAsync();
|
||||
|
||||
// assert
|
||||
Assert.NotNull(tools);
|
||||
Assert.NotEmpty(tools.Tools);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CallTool_Stdio_EchoServer()
|
||||
{
|
||||
// arrange
|
||||
|
||||
// act
|
||||
var client = await _fixture.Factory.GetClientAsync("test_server");
|
||||
var result = await client.CallToolAsync(
|
||||
"echo",
|
||||
new Dictionary<string, object>
|
||||
{
|
||||
["message"] = "Hello MCP!"
|
||||
},
|
||||
CancellationToken.None
|
||||
);
|
||||
|
||||
// assert
|
||||
Assert.NotNull(result);
|
||||
Assert.False(result.IsError);
|
||||
var textContent = Assert.Single(result.Content, c => c.Type == "text");
|
||||
Assert.Equal("Echo: Hello MCP!", textContent.Text);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ListResources_Stdio_TestServer()
|
||||
{
|
||||
// arrange
|
||||
|
||||
// act
|
||||
var client = await _fixture.Factory.GetClientAsync("test_server");
|
||||
|
||||
List<Resource> allResources = new();
|
||||
string? cursor = null;
|
||||
do
|
||||
{
|
||||
var resources = await client.ListResourcesAsync(cursor, CancellationToken.None);
|
||||
allResources.AddRange(resources.Resources);
|
||||
cursor = resources.NextCursor;
|
||||
}
|
||||
while (cursor != null);
|
||||
|
||||
// The everything server provides 100 test resources
|
||||
Assert.Equal(100, allResources.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReadResource_Stdio_TextResource()
|
||||
{
|
||||
// arrange
|
||||
|
||||
// act
|
||||
var client = await _fixture.Factory.GetClientAsync("test_server");
|
||||
// Odd numbered resources are text in the everything server (despite the docs saying otherwise)
|
||||
// 1 is index 0, which is "even" in the 0-based index
|
||||
// We copied this oddity to the test server
|
||||
var result = await client.ReadResourceAsync("test://static/resource/1", CancellationToken.None);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Single(result.Contents);
|
||||
Assert.NotNull(result.Contents[0].Text);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReadResource_Stdio_BinaryResource()
|
||||
{
|
||||
// arrange
|
||||
|
||||
// act
|
||||
var client = await _fixture.Factory.GetClientAsync("test_server");
|
||||
// Even numbered resources are binary in the everything server (despite the docs saying otherwise)
|
||||
// 2 is index 1, which is "odd" in the 0-based index
|
||||
// We copied this oddity to the test server
|
||||
var result = await client.ReadResourceAsync("test://static/resource/2", CancellationToken.None);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Single(result.Contents);
|
||||
Assert.NotNull(result.Contents[0].Blob);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ListPrompts_Stdio_TestServer()
|
||||
{
|
||||
// arrange
|
||||
|
||||
// act
|
||||
var client = await _fixture.Factory.GetClientAsync("test_server");
|
||||
var prompts = await client.ListPromptsAsync();
|
||||
|
||||
// assert
|
||||
Assert.NotNull(prompts);
|
||||
Assert.NotEmpty(prompts.Prompts);
|
||||
// We could add specific assertions for the known prompts
|
||||
Assert.Contains(prompts.Prompts, p => p.Name == "simple_prompt");
|
||||
Assert.Contains(prompts.Prompts, p => p.Name == "complex_prompt");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPrompt_Stdio_SimplePrompt()
|
||||
{
|
||||
// arrange
|
||||
|
||||
// act
|
||||
var client = await _fixture.Factory.GetClientAsync("test_server");
|
||||
var result = await client.GetPromptAsync("simple_prompt", null, CancellationToken.None);
|
||||
|
||||
// assert
|
||||
Assert.NotNull(result);
|
||||
Assert.NotEmpty(result.Messages);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPrompt_Stdio_ComplexPrompt()
|
||||
{
|
||||
// arrange
|
||||
|
||||
// act
|
||||
var client = await _fixture.Factory.GetClientAsync("test_server");
|
||||
var arguments = new Dictionary<string, object>
|
||||
{
|
||||
{ "temperature", 0.7 },
|
||||
{ "style", "formal" }
|
||||
};
|
||||
var result = await client.GetPromptAsync("complex_prompt", arguments, CancellationToken.None);
|
||||
|
||||
// assert
|
||||
Assert.NotNull(result);
|
||||
Assert.NotEmpty(result.Messages);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPrompt_NonExistent_ThrowsException()
|
||||
{
|
||||
// arrange
|
||||
|
||||
// act
|
||||
var client = await _fixture.Factory.GetClientAsync("test_server");
|
||||
await Assert.ThrowsAsync<McpClientException>(() =>
|
||||
client.GetPromptAsync("non_existent_prompt", null, CancellationToken.None));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Sampling_Stdio_TestServer()
|
||||
{
|
||||
// arrange
|
||||
var client = await _fixture.Factory.GetClientAsync("test_server");
|
||||
|
||||
// Set up the sampling handler
|
||||
int samplingHandlerCalls = 0;
|
||||
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
|
||||
client.SamplingHandler = async (_, _) =>
|
||||
{
|
||||
samplingHandlerCalls++;
|
||||
return new CreateMessageResult
|
||||
{
|
||||
Model = "test-model",
|
||||
Role = "assistant",
|
||||
Content = new Content
|
||||
{
|
||||
Type = "text",
|
||||
Text = "Test response"
|
||||
}
|
||||
};
|
||||
};
|
||||
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
|
||||
|
||||
// Call the server's sampleLLM tool which should trigger our sampling handler
|
||||
var result = await client.CallToolAsync(
|
||||
"sampleLLM",
|
||||
new Dictionary<string, object>
|
||||
{
|
||||
["prompt"] = "Test prompt",
|
||||
["maxTokens"] = 100
|
||||
}
|
||||
);
|
||||
|
||||
// assert
|
||||
Assert.NotNull(result);
|
||||
var textContent = Assert.Single(result.Content);
|
||||
Assert.Equal("text", textContent.Type);
|
||||
Assert.False(string.IsNullOrEmpty(textContent.Text));
|
||||
}
|
||||
}
|
||||
|
|
@ -153,7 +153,7 @@ public class SseIntegrationTests
|
|||
// Act
|
||||
var client = await factory.GetClientAsync("test_server");
|
||||
var mcpClient = (McpClient)client;
|
||||
var transport = (SseTransport)mcpClient.Transport;
|
||||
var transport = (SseClientTransport)mcpClient.Transport;
|
||||
|
||||
// Wait for SSE connection to be established
|
||||
await server.WaitForConnectionAsync(TimeSpan.FromSeconds(10));
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ public class SseTransportTests
|
|||
Location = "http://localhost:8080"
|
||||
};
|
||||
|
||||
var transportOptions = new SseTransportOptions
|
||||
var transportOptions = new SseClientTransportOptions
|
||||
{
|
||||
ConnectionTimeout = TimeSpan.FromSeconds(10),
|
||||
MaxReconnectAttempts = 2,
|
||||
|
|
@ -31,7 +31,7 @@ public class SseTransportTests
|
|||
};
|
||||
|
||||
// Act
|
||||
var transport = new SseTransport(transportOptions, config, NullLoggerFactory.Instance);
|
||||
var transport = new SseClientTransport(transportOptions, config, NullLoggerFactory.Instance);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(transport);
|
||||
|
|
@ -53,7 +53,7 @@ public class SseTransportTests
|
|||
Location = "http://localhost:8080"
|
||||
};
|
||||
|
||||
var transportOptions = new SseTransportOptions
|
||||
var transportOptions = new SseClientTransportOptions
|
||||
{
|
||||
ConnectionTimeout = TimeSpan.FromSeconds(10),
|
||||
MaxReconnectAttempts = 2,
|
||||
|
|
@ -65,7 +65,7 @@ public class SseTransportTests
|
|||
};
|
||||
|
||||
// Act
|
||||
var transport = new SseTransport(transportOptions, config, NullLoggerFactory.Instance);
|
||||
var transport = new SseClientTransport(transportOptions, config, NullLoggerFactory.Instance);
|
||||
|
||||
// Assert
|
||||
Assert.True(string.IsNullOrEmpty(transport.MessageEndpoint?.ToString()));
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
|
|
@ -27,6 +27,13 @@
|
|||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\mcpdotnet\mcpdotnet.csproj" />
|
||||
<ProjectReference Include="..\mcpdotnet.TestServer\mcpdotnet.TestServer.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Include="..\mcpdotnet.TestServer\bin\$(Configuration)\net8.0\TestServer.exe">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
Loading…
Reference in a new issue