How to Test MCP Servers in ASP.NET Core 10 Using C# – Unit Tests, Integration Tests and Security (2026)
A green unit test for a tool method says little about whether an MCP client can discover it, bind arguments, receive an error, or cancel the request. Those failures belong to different boundaries. A test suite becomes easier to debug when it tells you which boundary failed.
This tutorial builds a small ASP.NET Core 10 server and an xUnit suite with both pure C# tests and real Streamable HTTP integration tests. The example uses MCP C# SDK 2.3.1, the July 2026 protocol, and a read-only slug tool.
Which parts of an MCP server need tests?
| Layer | Use | Example assertion |
|---|---|---|
| Unit | Exercise deterministic application logic | Repeated spaces normalize to one hyphen |
| Protocol integration | Use the real SDK and transport | A registered tool appears and returns the expected content |
| HTTP security | Send a raw request to the host | Missing credentials and untrusted Origin are rejected |
| Deployment smoke test | Exercise actual ingress | HTTPS, buffering and disconnect behavior match expectations |
The suite uses no mock for the slug policy because it has no I/O. If the tool calls a database or a model, put the dependency behind an interface and use a small fake in unit tests. Test the real adapter separately against a disposable dependency. Mocking the MCP client in a protocol test would bypass precisely the serialization and transport behavior you want to cover.
Set up the projects
Install the .NET 10 SDK and create the layout below. The app project explicitly excludes the test source under tests. The test project references the server so it can exercise the public slug policy. Run the tests against a dedicated loopback instance, never a production endpoint.
The server uses the official ASP.NET Core MCP package. The test project gets the MCP Core types transitively from the server reference. Pinning versions makes it easier to reproduce protocol behavior. When upgrading the SDK, rerun transport tests alongside your package upgrade. The ASP.NET Core integration-testing documentation describes in-process hosting as another option. This lab uses a real loopback listener because stream closure matters to the cancellation test.
Implement the MCP tool and test boundary
Create Program.cs. The demo uses one random lab key, rejects browser-origin requests and binds to loopback. These checks deliberately create repeatable denial cases. For a remote deployment, use real caller authentication, scoped authorization, HTTPS, and request limits. The small delay creates an interval during which the integration test can cancel the call.
A slug is application data. The implementation deliberately restricts input to ASCII letters, digits and spaces. If a product needs Unicode slugs, define normalization, collision, and transliteration rules before changing the tests. Treat the slug as a display identifier unless you separately validate how it will be used in a filesystem or route.
Add unit and integration tests
Create tests/ServerTests.cs. The protocol test asserts the tool name and content type, then verifies invalid input produces an MCP tool error. The raw HTTP tests send a request without credentials and a request with an untrusted Origin. A 401 or 403 is different from an MCP tool error.
The cancellation test asserts the caller observes cancellation. It does not assert the server completed cleanup. For that stronger claim, instrument a completion signal inside a fake dependency or check a structured server log and prove that concurrency slots or temporary files are released. The lab uses a timer to create an observable cancellation window. Avoid treating the exact elapsed time as part of the contract.
Run the suite
Open two shells. Set the same random lab key in both without committing it or printing it. Make sure no other process is listening on port 5080.
Expected results include the slug hello-world, a tool error for the traversal-like input, and the two expected HTTP denial statuses. The server does not interpret ../secret as a path. The test asserts it rejects those characters.
All seven xUnit cases passed against a local .NET 10 loopback instance. The suite did not exercise a reverse proxy, legacy transports, or server-side cancellation cleanup.
Expand coverage with meaningful failure cases
A tool’s contract includes required fields, accepted types, limits, and the shape of its output. Add representative tests for malformed arguments, schema changes, and forbidden operations. Pin the protocol revision and include a separate compatibility run for any older client version you actually support. Use a unique resource identifier for each test so parallel tests cannot observe each other’s changes.
For tests with real writes, create a disposable database and assert state after an exception, timeout, and retry. A response can disappear after a commit. Use an idempotency key and inspect the durable result to check whether duplicate effects were prevented. Add a cross-tenant denial test wherever a tool accesses user-owned data. Deny both direct identifier substitution and a mismatched token audience.
In a CI pipeline, allocate a unique local port or run one listener per isolated job. Wait for readiness with a bounded polling loop. Stop the host in cleanup even when a test fails. Treat logs as diagnostic artifacts and remove credentials, raw prompts, and private fixtures before publishing them.
Troubleshooting
| Symptom | First check |
|---|---|
| Connection refused | Dedicated host and port |
| All protocol calls return unauthorized | Same key in both process environments |
| Tool list is empty | Tool attributes and registration |
| Test passes despite a tool error | Assert IsError as well as content |
| Cancellation test flakes in CI | Use a controlled signal to ensure work started before canceling |
Frequently asked questions
Should I mock the MCP transport?
A mock can exercise an application component’s behavior, but keep at least one test that uses the real MCP protocol. Tool registration and argument binding can fail while direct method tests pass.
Does one test cover authorization?
One test covers one rule. Include missing, invalid, expired, and wrong-audience credentials for an authenticated deployment. Verify tenant authorization independently after authentication.
Can an HTTP 200 represent a failed tool call?
Yes. Check the MCP result for a tool error. Protocol success and business success describe different layers.
Conclusion and references
Start with deterministic policy tests, then exercise a real SDK call and the denial paths at the HTTP boundary. These checks complement the ASP.NET PB MCP server guide.
Comments
Post a Comment