You are viewing a plain text version of this content. The canonical link for it is here.
Posted to java-commits@axis.apache.org by ro...@apache.org on 2026/04/06 23:30:54 UTC
(axis-axis2-java-core) 09/10: mcp: A1/A2/A3 complete — /openapi-mcp.json, mcp-bridge stdio JAR, mTLS, X.509 auth, unit tests
This is an automated email from the ASF dual-hosted git repository.
robertlazarski pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/axis-axis2-java-core.git
commit 70fcdd2821ace5d3a96ee489ad7b697acca7b98a
Author: Robert Lazarski <ro...@gmail.com>
AuthorDate: Mon Apr 6 13:04:17 2026 -1000
mcp: A1/A2/A3 complete — /openapi-mcp.json, mcp-bridge stdio JAR, mTLS, X.509 auth, unit tests
Track A (OpenAPI-driven MCP bridge) is fully implemented and validated:
A1 — /openapi-mcp.json endpoint (axis2-openapi module)
- OpenApiSpecGenerator.generateMcpCatalogJson(): iterates AxisConfiguration services
with same isSystemService/shouldIncludeService/shouldIncludeOperation filters as
generatePaths(); produces MCP tool catalog JSON
- SwaggerUIHandler.handleMcpCatalogRequest(): mirrors handleOpenApiJsonRequest()
with application/json content-type, CORS headers, security headers
- OpenApiServlet + Axis2WebAppInitializer: route /openapi-mcp.json to handler
- Axis2Application.OPENAPI_PATHS: added /openapi-mcp.json to bypass JWT chain
A2 — axis2-mcp-bridge stdio JAR (new module modules/mcp-bridge/)
- McpTool: data class, strips HTTP method prefix to derive path
- ToolRegistry: GETs /openapi-mcp.json at startup, builds List<McpTool>/Map
- McpStdioServer: blocking stdin loop, JSON-RPC 2.0 dispatch
(initialize / tools/list / tools/call / error / notification handling)
- McpBridgeMain: --base-url / --keystore / --truststore arg parsing,
buildSslContext() for PKCS12 mTLS; maven-shade produces *-exe.jar uber-jar
- No MCP SDK — Jackson 2.21.1 (Apache 2.0) + Java stdlib HttpClient only
- Protocol version: 2024-11-05; notifications silently consumed (no response)
mTLS / PKI
- IoT CA pattern: RSA 4096 CA (10yr) + RSA 2048 leaf certs (2yr), SHA-256, PKCS12
- certs/: ca.{key,crt}, server.{key,crt,csr}, client.{key,crt,csr},
server-keystore.p12, ca-truststore.p12, client-keystore.p12 (password: changeit)
- Tomcat 8443 connector: certificateVerification=required, TLSv1.2+
X.509 Spring Security (springbootdemo-tomcat11)
- X509AuthenticationFilter: reads jakarta.servlet.request.X509Certificate (set by
Tomcat post-handshake), extracts CN via RFC 2253, creates
UsernamePasswordAuthenticationToken(CN, cert, [ROLE_X509_CLIENT])
- springSecurityFilterChainMtls @Order(2): MtlsRequestMatcher (port==8443),
X509AuthenticationFilter ahead of existing JWT chains
A3 validation — confirmed working end-to-end:
Claude Desktop -> axis2-mcp-bridge stdio -> HTTPS+mTLS 8443
-> X509AuthenticationFilter (CN=axis2-mcp-bridge, ROLE_X509_CLIENT)
-> BigDataH2Service.processBigDataSet() -> real response returned
Unit tests (JUnit 3 TestCase style, matching existing openapi module conventions)
mcp-bridge module (4 new test classes, 48 tests):
McpToolTest: path extraction, description fallback, accessor correctness
McpStdioServerTest: initialize/tools-list/unknown-method/parse-error/notification/
sequence tests via System.in/out redirection + StubToolRegistry inner class
McpBridgeMainTest: parseArg/parseArgOrDefault via reflection, buildSslContext
with real cert files (skips gracefully when certs absent)
ToolRegistryTest: pre-load state, injection via reflection, ParseableRegistry
subclass driving catalog-parsing logic for 7 parsing scenarios
openapi module (2 new test classes, 26 tests):
McpCatalogGeneratorTest: JSON validity, empty catalog, tool fields, endpoint format,
inputSchema structure, JSON escaping, MCP/OpenAPI path consistency
McpCatalogHandlerTest: HTTP 200, Content-Type, CORS headers, body validity,
service discovery, security header presence
MCP.md updated: current state table, PKI section, Spring Security filter chain table,
X.509 auth flow, next steps (C1 now unblocked, A4/Track B queued)
Co-Authored-By: Claude Sonnet 4.6 <no...@anthropic.com>
---
MCP.md | 285 +++++++++-----
certs/ca-truststore.p12 | Bin 0 -> 1766 bytes
certs/ca.crt | 31 ++
certs/ca.key | 52 +++
certs/ca.srl | 1 +
certs/client-keystore.p12 | Bin 0 -> 4404 bytes
certs/client.crt | 26 ++
certs/client.csr | 16 +
certs/client.key | 28 ++
certs/server-keystore.p12 | Bin 0 -> 4412 bytes
certs/server.crt | 26 ++
certs/server.csr | 16 +
certs/server.key | 28 ++
modules/mcp-bridge/pom.xml | 113 ++++++
.../org/apache/axis2/mcp/bridge/McpBridgeMain.java | 143 +++++++
.../apache/axis2/mcp/bridge/McpStdioServer.java | 247 ++++++++++++
.../java/org/apache/axis2/mcp/bridge/McpTool.java | 60 +++
.../org/apache/axis2/mcp/bridge/ToolRegistry.java | 119 ++++++
.../apache/axis2/mcp/bridge/McpBridgeMainTest.java | 187 +++++++++
.../axis2/mcp/bridge/McpStdioServerTest.java | 429 +++++++++++++++++++++
.../org/apache/axis2/mcp/bridge/McpToolTest.java | 145 +++++++
.../apache/axis2/mcp/bridge/ToolRegistryTest.java | 323 ++++++++++++++++
.../apache/axis2/openapi/OpenApiSpecGenerator.java | 76 ++++
.../org/apache/axis2/openapi/SwaggerUIHandler.java | 32 ++
.../axis2/openapi/McpCatalogGeneratorTest.java | 421 ++++++++++++++++++++
.../axis2/openapi/McpCatalogHandlerTest.java | 303 +++++++++++++++
.../userguide/springboot/Axis2Application.java | 37 +-
.../configuration/Axis2WebAppInitializer.java | 4 +-
.../springboot/configuration/OpenApiServlet.java | 2 +
.../webservices/X509AuthenticationFilter.java | 111 ++++++
30 files changed, 3157 insertions(+), 104 deletions(-)
diff --git a/MCP.md b/MCP.md
index 540e749c2c..b6ecfd7bfc 100644
--- a/MCP.md
+++ b/MCP.md
@@ -1,14 +1,15 @@
---
type: architecture
created: 2026-04-06
-status: Active — pre-implementation
+last-verified: 2026-04-06
+status: Active — A1/A2/A3 complete, mTLS validated
---
# MCP Support for Apache Axis2/Java
**BLUF**: Axis2/Java gains MCP (Model Context Protocol) support in two phases. Phase A
(practical, immediate) wraps an existing Axis2 deployment with a bridge that reads
-`/openapi-mcp.json` and proxies MCP `tools/call` to Axis2 over HTTP. Phase B (native,
+`/openapi-mcp.json` and proxies MCP `tools/call` to Axis2 over HTTPS+mTLS. Phase B (native,
novel Apache contribution) implements `axis2-transport-mcp` so Axis2 speaks MCP
directly — no wrapper. One service deployment, three protocols: JSON-RPC, REST, MCP.
@@ -25,128 +26,194 @@ modelcontextprotocol.io.
| Artifact | Status | Notes |
|----------|--------|-------|
-| `springbootdemo-tomcat11` | ✅ Working | Spring Boot 3.x + Axis2 + Tomcat 11 + Java 25, end-to-end tested |
+| `springbootdemo-tomcat11` | ✅ Working | Spring Boot 3.x + Axis2 + Tomcat 11 + Java 25 |
| `axis2-openapi` module | ✅ Working | Serves `/openapi.json`, `/openapi.yaml`, `/swagger-ui` |
-| `modules/transport-h2` | ✅ Tested | HTTP/2 transport PoC, `BigDataH2Service` confirmed working |
-| ThreadPool instance-field fix | ✅ Committed | `27860ddf9f` — static→instance, fixes multi-pool JVM isolation |
+| `/openapi-mcp.json` endpoint | ✅ Done | `OpenApiSpecGenerator.generateMcpCatalogJson()` + `SwaggerUIHandler.handleMcpCatalogRequest()` |
+| `axis2-mcp-bridge` stdio JAR | ✅ Done | `modules/mcp-bridge/`, produces `*-exe.jar` uber-jar |
+| mTLS transport | ✅ Done | Tomcat 8443, `certificateVerification="required"`, IoT CA pattern |
+| X.509 Spring Security | ✅ Done | `X509AuthenticationFilter` at `@Order(2)`, CN → `ROLE_X509_CLIENT` |
+| A3 end-to-end validation | ✅ Done | `Claude Desktop → bridge → mTLS 8443 → BigDataH2Service` confirmed |
| `axis2-spring-boot-starter` | ❌ Not started | Phase 1 of modernization plan |
-| `/openapi-mcp.json` endpoint | ❌ Not started | Requires work in `axis2-openapi` module |
-| `axis2-mcp-bridge` | ❌ Not started | Thin bridge JAR, reads MCP catalog, proxies to Axis2 |
-| `axis2-transport-mcp` | ❌ Not started | Native MCP transport — novel Apache contribution |
+| A4 HTTP/SSE transport | ❌ Not started | Post-demo, deferred |
+| `axis2-transport-mcp` native | ❌ Not started | Track B — novel Apache contribution |
### Reference implementation
```
-springbootdemo-tomcat11 base URL: http://localhost:8080/axis2-json-api
+springbootdemo-tomcat11 base URL: https://localhost:8443/axis2-json-api
Services deployed:
- - LoginService (auth)
- - BigDataH2Service (streaming/multiplexing demo)
+ - LoginService (auth, port 8080 only)
+ - BigDataH2Service (streaming/multiplexing demo, accessible via mTLS on 8443)
```
-`BigDataH2Service` request format (confirmed working):
+`BigDataH2Service` request format (confirmed working via MCP bridge):
```json
{"processBigDataSet":[{"request":{"datasetId":"test-dataset-001","datasetSize":1048576}}]}
```
---
-## Track A — OpenAPI-Driven MCP Bridge
+## Security Architecture
+
+### PKI (IoT CA Pattern)
+
+Certificates live in `/home/robert/repos/axis-axis2-java-core/certs/`. The CA follows
+the same pattern as the Kanaha camera project — RSA 4096 CA with RSA 2048 leaf certs,
+appropriate for IoT/embedded where certificate management is manual.
+
+| File | Contents | Validity |
+|------|----------|---------|
+| `ca.key` / `ca.crt` | Root CA, `CN=Axis2 CA, O=Apache Axis2, OU=IoT Services` | 10 years |
+| `server.key` / `server.crt` | Server cert, `CN=localhost`, SAN: `DNS:localhost, IP:127.0.0.1` | 2 years |
+| `server-keystore.p12` | Tomcat server keystore (server cert + key + CA chain) | — |
+| `ca-truststore.p12` | Tomcat truststore (CA cert only) | — |
+| `client.key` / `client.crt` | Client cert, `CN=axis2-mcp-bridge`, `extendedKeyUsage=clientAuth` | 2 years |
+| `client-keystore.p12` | Bridge client keystore (client cert + key + CA chain) | — |
+
+Keystores are also copied to `/home/robert/apache-tomcat-11.0.20/conf/`.
+
+Password for all PKCS12 files: `changeit`
+
+### Tomcat mTLS Connector (port 8443)
+
+`server.xml` connector in `/home/robert/apache-tomcat-11.0.20/conf/server.xml`:
+
+```xml
+<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
+ maxThreads="150" SSLEnabled="true">
+ <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
+ <SSLHostConfig certificateVerification="required"
+ truststoreFile="conf/ca-truststore.p12"
+ truststorePassword="changeit"
+ truststoreType="PKCS12"
+ protocols="TLSv1.2+">
+ <Certificate certificateKeystoreFile="conf/server-keystore.p12"
+ certificateKeystorePassword="changeit"
+ certificateKeystoreType="PKCS12"
+ type="RSA" />
+ </SSLHostConfig>
+</Connector>
+```
+
+Plain HTTP port 8081 is commented out. All traffic goes through 8443.
+
+### Spring Security Filter Chain
+
+The filter chains in `Axis2Application.java` are ordered:
+
+| Order | Chain | Matcher | Auth |
+|-------|-------|---------|------|
+| 1 | `springSecurityFilterChain` (default) | Everything | JWT |
+| 2 | `springSecurityFilterChainMtls` | Port 8443 (`MtlsRequestMatcher`) | X.509 cert |
+| 3 | `springSecurityFilterChainOpenApi` | `/openapi.json`, `/openapi.yaml`, `/swagger-ui`, `/openapi-mcp.json` | None |
+| 4 | `springSecurityFilterChainLogin` | `/services/LoginService/**` | None |
-**When**: Immediate next work session. No dependency on native transport.
+The `@Order(2)` mTLS chain intercepts all 8443 requests before the JWT chain.
+`X509AuthenticationFilter` reads `jakarta.servlet.request.X509Certificate` (set by
+Tomcat after the TLS handshake), extracts the CN, and creates an
+`UsernamePasswordAuthenticationToken` with `ROLE_X509_CLIENT`. The existing
+`GenericAccessDecisionManager.decide()` is a no-op, so any authenticated principal
+passes `FilterSecurityInterceptor`.
-**Why first**: The team already knows MCP. This gives them a working demo calling
-existing Axis2 services through Claude/Cursor without writing MCP-specific service code.
+### X.509 Authentication Flow
-### A1 — `/openapi-mcp.json` endpoint in `axis2-openapi`
+```
+Client presents cert → Tomcat TLS handshake (certificateVerification=required)
+ → Only CA-signed certs pass
+ → Tomcat writes cert chain to jakarta.servlet.request.X509Certificate attribute
+ → X509AuthenticationFilter.doFilter()
+ → Extract CN (e.g., "axis2-mcp-bridge")
+ → SecurityContextHolder.getContext().setAuthentication(token)
+ → FilterSecurityInterceptor: authenticated → passes
+ → Service handler executes
+```
+
+---
+
+## Track A — OpenAPI-Driven MCP Bridge
-**File**: `modules/openapi/src/main/java/org/apache/axis2/openapi/`
+### A1 — `/openapi-mcp.json` endpoint ✅ Done
-Add `McpToolCatalogServlet` alongside the existing `OpenApiServlet`. Endpoint returns:
+**Implementation**: `OpenApiSpecGenerator.generateMcpCatalogJson(HttpServletRequest)` iterates
+`AxisConfiguration.getServices()` using the same `isSystemService()` / `shouldIncludeService()` /
+`shouldIncludeOperation()` filters as the existing OpenAPI path generation. Output:
```json
{
"tools": [
{
"name": "processBigDataSet",
- "description": "Process a large dataset using HTTP/2 multiplexing",
- "inputSchema": {
- "type": "object",
- "properties": {
- "datasetId": { "type": "string" },
- "datasetSize": { "type": "integer" }
- },
- "required": ["datasetId", "datasetSize"]
- },
+ "description": "BigDataH2Service: processBigDataSet",
+ "inputSchema": { "type": "object", "properties": {}, "required": [] },
"endpoint": "POST /services/BigDataH2Service/processBigDataSet"
}
]
}
```
-Implementation strategy:
-- Inject `ConfigurationContext` via `getServletContext().getAttribute(AxisServlet.CONFIGURATION_CONTEXT)`
-- Iterate `ctx.getAxisConfiguration().getServices()` → each `AxisService`
-- Iterate `service.getOperations()` → each `AxisOperation`
-- Use existing `axis2-openapi` reflection infrastructure for schema extraction
-- Add optional `@McpTool(description = "...")` annotation for richer descriptions
+**Routing**: `OpenApiServlet.java` dispatches `uri.endsWith("/openapi-mcp.json")` to
+`handler.handleMcpCatalogRequest()`. `Axis2WebAppInitializer.java` maps the path.
+`Axis2Application.java` `OPENAPI_PATHS` array includes `/openapi-mcp.json` so the
+OpenAPI filter chain (`@Order(3)`) handles it without auth.
-**Estimated effort**: 2–3 days.
+### A2 — `axis2-mcp-bridge` stdio JAR ✅ Done
-### A2 — `axis2-mcp-bridge` stdio server
+**Location**: `modules/mcp-bridge/`
-**Location**: New module `modules/mcp-bridge/` or standalone JAR.
+**Key decision**: No MCP Java SDK (Apache 2.0 license constraint — SDK license
+uncertain at implementation time). JSON-RPC 2.0 is implemented directly using
+Jackson 2.21.1 (Apache 2.0) + Java stdlib `HttpClient`. The three-method
+handshake is straightforward enough to hand-roll correctly.
-Startup (Claude Desktop `~/.config/claude/claude_desktop_config.json`):
+**Classes**:
+- `McpBridgeMain` — entry point, parses `--base-url`, `--keystore`, `--truststore` args, builds `SSLContext`, starts registry + server
+- `ToolRegistry` — GETs `{baseUrl}/openapi-mcp.json` at startup, builds `List<McpTool>` and `Map<String,McpTool>`
+- `McpStdioServer` — blocking stdin read loop, JSON-RPC 2.0 dispatch
+- `McpTool` — data class: name, description, inputSchema (JsonNode), endpoint, path
+
+**Build**: maven-shade-plugin 3.6.0 produces `axis2-mcp-bridge-2.0.1-SNAPSHOT-exe.jar`
+(classifier: `exe`) with `MainClass=McpBridgeMain`.
+
+**Axis2 JSON-RPC envelope**: `tools/call` wraps arguments as `{toolName: [arguments]}`
+before POSTing to the Axis2 endpoint, matching the existing JSON-RPC convention.
+
+**Notifications**: MCP `notifications/initialized` (no `id` field) is silently consumed
+with no response, as required by JSON-RPC 2.0.
+
+**Protocol version**: `"2024-11-05"`
+
+**Claude Desktop config** (`~/.config/claude/claude_desktop_config.json`):
```json
{
"mcpServers": {
"axis2-demo": {
"command": "java",
- "args": ["-jar", "/path/to/axis2-mcp-bridge.jar",
- "--base-url", "http://localhost:8080/axis2-json-api"]
+ "args": ["-jar", "/path/to/axis2-mcp-bridge-2.0.1-SNAPSHOT-exe.jar",
+ "--base-url", "https://localhost:8443/axis2-json-api",
+ "--keystore", "/home/robert/repos/axis-axis2-java-core/certs/client-keystore.p12",
+ "--truststore", "/home/robert/repos/axis-axis2-java-core/certs/ca-truststore.p12"]
}
}
}
```
-Core loop:
-1. Fetch `{base-url}/openapi-mcp.json` at startup → build tool registry
-2. Read JSON-RPC 2.0 lines from `System.in`
-3. `initialize` → return server info + tool capabilities
-4. `tools/list` → return registry
-5. `tools/call` → `HttpClient.send(POST to Axis2 endpoint)` → return result
-6. Write JSON-RPC 2.0 response to `System.out`
-
-Use the official MCP Java SDK to handle `initialize` capability negotiation rather than
-hand-rolling it. Community Java port: `io.modelcontextprotocol:sdk` (check Maven Central
-for latest coordinates).
+### A3 — End-to-end validation ✅ Done
-**Do not** hand-roll JSON-RPC framing — the initialize/capability handshake has version
-negotiation subtleties that the SDK handles correctly.
-
-**Estimated effort**: 3–4 days.
-
-### A3 — Team validation against `springbootdemo-tomcat11`
-
-Quick smoke-test script:
-```bash
-#!/bin/bash
-# Initialize
-echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}' \
- | java -jar axis2-mcp-bridge.jar --base-url http://localhost:8080/axis2-json-api
-
-# List tools
-echo '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}' \
- | java -jar axis2-mcp-bridge.jar --base-url http://localhost:8080/axis2-json-api
-
-# Call a tool
-echo '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"processBigDataSet","arguments":{"datasetId":"mcp-test-001","datasetSize":1048576}}}' \
- | java -jar axis2-mcp-bridge.jar --base-url http://localhost:8080/axis2-json-api
+Full chain confirmed working:
+```
+Claude Desktop → axis2-mcp-bridge stdio → HTTPS+mTLS port 8443
+ → Tomcat TLS handshake (client cert CN=axis2-mcp-bridge)
+ → X509AuthenticationFilter (authenticated, ROLE_X509_CLIENT)
+ → BigDataH2Service.processBigDataSet()
+ → real response returned to Claude
```
-**Estimated effort**: 1–2 days.
+Tomcat log confirmation:
+```
+X509AuthenticationFilter: authenticated CN=axis2-mcp-bridge on port 8443
+```
-### A4 — HTTP/SSE transport (post-demo, deferred)
+### A4 — HTTP/SSE transport (deferred)
Adds persistent server mode (multiple Claude sessions sharing one bridge). Required for
production. Additive — no changes to Axis2 side or tool catalog format.
@@ -228,15 +295,55 @@ decouples the bridge from Axis2 internals. The bridge works against any HTTP ser
that serves this format — not just Axis2. This is useful for the Apache community
beyond the Axis2 user base.
+**Why no MCP Java SDK**: Apache 2.0 license constraint. Jackson (Apache 2.0) + Java
+stdlib `HttpClient` implement the three-method JSON-RPC 2.0 protocol without external
+dependencies whose license compatibility is uncertain. The protocol is well-specified
+enough to hand-roll correctly.
+
+**Why IoT CA pattern**: RSA 4096 CA (10 years) + RSA 2048 leaf certs (2 years) matches
+the Kanaha camera project pattern. Appropriate for environments where certificate
+management is manual and infrequent. The CA is only on one machine — this is a
+development/demo CA, not a production CA.
+
+**Why `certificateVerification="required"` at Tomcat, not Spring Security**: Tomcat
+enforces the TLS handshake before any HTTP processing. Invalid client certs are rejected
+at the TCP layer — Spring Security never sees them. `X509AuthenticationFilter` only
+needs to extract identity from an already-verified cert, not verify it.
+
**Why not JAX-RS instead of `@RestMapping`**: JAX-RS brings a second framework
dependency and its own lifecycle. `@RestMapping` is a thin annotation processed by
Axis2's existing REST dispatcher — no container dependency, backwards compatible,
opt-in per-operation.
-**Why not Spring AI or LangChain4j as the MCP layer**: Those are application-layer
-frameworks. The goal is transport-level integration so Axis2 services are callable from
-*any* MCP client, not just Spring-based applications. `axis2-transport-mcp` is at the
-right abstraction level.
+---
+
+## Next Steps
+
+### Immediate — C port is now unblocked
+
+Java A2 is validated against Claude Desktop. The Axis2/C `financial_benchmark_service`
+can now implement C1 (stdio MCP mode) in parallel with any Java Track B work.
+
+See `docs/MCP.md` in the `axis-axis2-c-core` repo for the C1 plan.
+
+### Track A remaining
+
+| Step | Work | Notes |
+|------|------|-------|
+| `@McpTool` annotation | Richer `inputSchema` in `/openapi-mcp.json` | Currently all tools return empty properties `{}` |
+| A4 HTTP/SSE | Persistent bridge server mode | Required for production, additive |
+
+### Track B
+
+1. `modules/transport-mcp/` — new module scaffolding
+2. stdio transport first (B1) — validates JSON-RPC 2.0 ↔ MessageContext translation
+3. HTTP/SSE transport (B2) — reuses Axis2 HTTP infrastructure
+
+### Penguin demo
+
+`build_financial_service.sh` in `axis-axis2-c-core` needs to be run on the Penguin
+host after Axis2/C is installed. The service is committed and compiles clean — the
+script is the only remaining deployment step.
---
@@ -244,29 +351,11 @@ right abstraction level.
Track A (`axis2-mcp-bridge`) requires:
- `axis2-openapi` module (for `/openapi-mcp.json`)
-- MCP Java SDK (check coordinates at time of implementation)
+- `com.fasterxml.jackson.core:jackson-databind:2.21.1` (Apache 2.0)
- Java 21+ (HttpClient is standard library)
- No Axis2 core dependency — bridge is a separate process
Track B (`axis2-transport-mcp`) requires:
- `axis2-core` / `axis2-kernel` (TransportListener interface)
- `axis2-openapi` (tool schema generation)
-- MCP Java SDK (JSON-RPC 2.0 framing)
-
-Both tracks require `axis2-spring-boot-starter` (Phase 1) to wire transport config
-via `application.properties`.
-
----
-
-## Next Immediate Actions
-
-1. **Start A1**: Add `McpToolCatalogServlet` to `modules/openapi/`. Start with
- structural introspection (no annotation support yet) — get `/openapi-mcp.json`
- serving a valid tool list from `springbootdemo-tomcat11`.
-
-2. **Check MCP Java SDK coordinates**: Verify artifact ID and version on Maven Central
- before starting A2. The protocol is at `modelcontextprotocol.io/specification`.
-
-3. **Penguin demo (Track C, parallel)**: The Axis2/C financial benchmark service is
- committed and compiles clean. When Penguin demo prep begins, the service is ready —
- just needs `build_financial_service.sh` run on the Penguin host after Axis2/C install.
+- No MCP SDK — same Jackson-only approach as A2
diff --git a/certs/ca-truststore.p12 b/certs/ca-truststore.p12
new file mode 100644
index 0000000000..d08772e58f
Binary files /dev/null and b/certs/ca-truststore.p12 differ
diff --git a/certs/ca.crt b/certs/ca.crt
new file mode 100644
index 0000000000..31f7ccea1e
--- /dev/null
+++ b/certs/ca.crt
@@ -0,0 +1,31 @@
+-----BEGIN CERTIFICATE-----
+MIIFYzCCA0ugAwIBAgIUSXUAOQ/TXCKneEPsfNSziMPkHG8wDQYJKoZIhvcNAQEL
+BQAwQTERMA8GA1UEAwwIQXhpczIgQ0ExFTATBgNVBAoMDEFwYWNoZSBBeGlzMjEV
+MBMGA1UECwwMSW9UIFNlcnZpY2VzMB4XDTI2MDQwNjE3NDkxM1oXDTM2MDQwMzE3
+NDkxM1owQTERMA8GA1UEAwwIQXhpczIgQ0ExFTATBgNVBAoMDEFwYWNoZSBBeGlz
+MjEVMBMGA1UECwwMSW9UIFNlcnZpY2VzMIICIjANBgkqhkiG9w0BAQEFAAOCAg8A
+MIICCgKCAgEAvQ3CNQVQmXqqXFazYVjeSxA80VINNqnG30eJPYsZaWO0h1QnEeJv
+WpNGK/xJx+x+wcfTj+Ie0fhR2SROFmmTHxp2x0KLaIkryn6cggfzGVe2AmYo5CrZ
+5gS+1ZUFCjm2/CBYxH66sR6iczG0/g/zQbUy1xhceIRbY3qnD/HT8wK492RL6lAm
+LHThbd6m6ywLWGakzS9FItv6P1LV3MoeMRBTz+Ptn8iKYgmqincJkHHyHt7q/FrW
+pVF1xJxU1lmLugxjfPec4CiJajEVG8B0o+hHJA19uQgsiydg5/VhW2nhoi157f+s
+1sNncFXzFclL0f3FdKvZPh+jZI8Y9gDuKHhIb66lwNdE4NCLdRdz5HLkdMcH6za9
+tvu4Vmu50xP8FPHgAZqTSsgMoEUv7BJyV2ymEVWYKvGHHhMsUgw7aHSPbUDJ1rA9
+3X5xaZ+HyVPU09XVt3ZVcKZHuJx3o/h7TibQvXfV3TrKbhB0zuyDnYH9IBtk1pdf
+uWdZs6fN9J4k1rSSRPP/TDkou6NDf4g+fkfx6sNfApnsRvGKJhnJTUR/vFzUQRVK
+FeWXd//etMrubMH452iA8o5hVZqXconynrrEAEKfh/WRAKwfubgUrNF7QpyUDaLD
+Ukr3T+4uCVndOu9kr2t/UA3FAjMVRTvdTxZfbwdQqiumyQBF+k5p7fsCAwEAAaNT
+MFEwHQYDVR0OBBYEFODmuumf3wUCHVpXb5b2/iXPF1ozMB8GA1UdIwQYMBaAFODm
+uumf3wUCHVpXb5b2/iXPF1ozMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEL
+BQADggIBALn9SZbmJGhgHKfNr9+Lfo7ejCeJrCfhLy5DuBIesOcR3OEHEndFLWIn
+iNgVwsV9Z+HOwbwmDt4MHPtSO6537E+PTOoWuEK49THZM4ql5E/YP0+kwbQCfhFb
+OsspROQlXfdgttqWNpiQN8dqKrle8X0RrLUAh++JUD3S2aTXIGUVo3bQjZAckv0/
+sHV+oKnuAyynCOxRcZeZ3K+0H+GGTrhEcc+ohwbIy+O1B94QNhpg4uirif7SzgaM
+Z2GiXvT9Mjd7uCYOsPcDsTvixAAVUFbNl/xlqzwLmm1LcsPJFK08zXTIVBT7dp7O
+yGT2dTk5o7azI43NDMiXJgHi4H/D7DOGckYjE62NCxnWVS0dyrsRemCN75oKq3Mb
+dyVFvqAsZiQTyn5zB7cjuZQ2ygf5g7zIwScjHjWDZdSzp1zvcT30ygD7ilgjXq2v
+SyUWsz4FNPIpHBOoxJep+y63B3KrKyYKKOuZ6lMHa4zS2aJ80Bn8tG5+wVfxE5KZ
+REp24gdjADKkYw/Hlq4GxTGLmTZ4a3WvClqPz0kMAsawA2w67BmPjitrnAMblqcu
+SwgjhapwIJk/SXIoT19UkCco0pjGcL/R2WVUTEnNn1zLo8mpls8VFHAxWM3UYctL
+GkBg0YHG/2eCE+VDM9sTCdHPHaJUkDhNw/mSdPHi7DBr697o1BDc
+-----END CERTIFICATE-----
diff --git a/certs/ca.key b/certs/ca.key
new file mode 100644
index 0000000000..b75f58413f
--- /dev/null
+++ b/certs/ca.key
@@ -0,0 +1,52 @@
+-----BEGIN PRIVATE KEY-----
+MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQC9DcI1BVCZeqpc
+VrNhWN5LEDzRUg02qcbfR4k9ixlpY7SHVCcR4m9ak0Yr/EnH7H7Bx9OP4h7R+FHZ
+JE4WaZMfGnbHQotoiSvKfpyCB/MZV7YCZijkKtnmBL7VlQUKObb8IFjEfrqxHqJz
+MbT+D/NBtTLXGFx4hFtjeqcP8dPzArj3ZEvqUCYsdOFt3qbrLAtYZqTNL0Ui2/o/
+UtXcyh4xEFPP4+2fyIpiCaqKdwmQcfIe3ur8WtalUXXEnFTWWYu6DGN895zgKIlq
+MRUbwHSj6EckDX25CCyLJ2Dn9WFbaeGiLXnt/6zWw2dwVfMVyUvR/cV0q9k+H6Nk
+jxj2AO4oeEhvrqXA10Tg0It1F3PkcuR0xwfrNr22+7hWa7nTE/wU8eABmpNKyAyg
+RS/sEnJXbKYRVZgq8YceEyxSDDtodI9tQMnWsD3dfnFpn4fJU9TT1dW3dlVwpke4
+nHej+HtOJtC9d9XdOspuEHTO7IOdgf0gG2TWl1+5Z1mzp830niTWtJJE8/9MOSi7
+o0N/iD5+R/Hqw18CmexG8YomGclNRH+8XNRBFUoV5Zd3/960yu5swfjnaIDyjmFV
+mpdyifKeusQAQp+H9ZEArB+5uBSs0XtCnJQNosNSSvdP7i4JWd0672Sva39QDcUC
+MxVFO91PFl9vB1CqK6bJAEX6Tmnt+wIDAQABAoICAAYWEc5UKqPuQ4Vv0xw2A14G
+RUxLKHATPNBGWiA4QKwDEODvGseOyHKcMtJKr8i3D95G2RmU4tTJT5U+f8xlP15t
+Iy1yB9E94peFG55stBejmmaZtFpNbjC4rrjAheYuNSUJGOJ73qBsxze502+pwsqM
+PflCaFkG5cxI5WT0Lj8bXioKDrmZ3/Nmxd/Gybfgy0gKxzvFzaN8J80Zv8HOY0oa
+vPVV4KStYkBwEDn0msMNhV5suG2XB7mlwDVWqmfbf83lr97qN8uC8pLlG/QF7kYH
+6HZm1XPQqWJyH5gIGcdwHAVKZ9ZQzgHR+PFbCwAvYqNS2KRTaKMr2z5AWcIzBc0L
+PAFiwCYmJlAPTBm/xNInyNk/wlTypJ1t03vM0YBtjvq2asgUgIwE0KQ8uAHEyrfK
+ZWlolCCejmxzg/S8Qv/Ax+NHxjhW52P+uOoQJszz18UfvLxX8rzQCXZW9RuxUHaz
+cuJwEzEQT/MZ8F/CpTNE2j5akNLfoJ1/lzCHTyhs1k8VF2849ZT0K9RFOHTbk1tS
+1AH62FRcS8cy9lrGyDqhtxu0Yqu6U27wsFkgTlQDbUU0GvhUmxT+Ke4Q0Ds/VviD
+IV1N5ll8SsoHy3GJA256lI8n56DtGgVg2/xGVJgU0HoznLFXMcmV1jyE9xY9Xj+g
+ml72ff/p6ljJ/iyOkOFJAoIBAQDdaghFg6DDli0lWuIEcSaR6Br6GWxILvoqKrQt
+Cp+efhI4Bov7nh4A60SsjjFWkHHu0OCBrEhqW4p4j7rCPb31IjZyxXEbbcZ/7cbq
+6lKGEwXfXwPqERuu92gtaSvyL3uTveM1FFWKGBvKQFJ7KC8+Y2VbnlV8y/AQBL8J
+4cmd5+HvTGhxsOX8AlNSG4L6DGyOC9Cz36jzhpL9C/D3vvtoYaF3Yc0xJBkKpVgT
+oNVeiVD1VaYZD2kkqguWtG9yE/5Cvs8sNUplO7FcjRIZGBdMxo78ih2JWc90uDLE
+NyN+mtP1PlxjxJOZamYIaKvvNJ1YtzQS8pmRgYbiltB2KfpJAoIBAQDalbBDMPDH
+sJ4ol4Xid7L8d86DZE8MIseavWzR8003KByk1rWhyzCd4GqJnfgx8c1ANa1SAYon
+BqYdfAWooA2TWWNqrtIKisdIVprzxGFZpsAhJpbUWesbZfKCQRakItlwzk+oqbsy
+duWr2P6NwTO7pC4KwpaloWGSyMHBvBHs4HJdtcbITP6L18nYa0IY/7ThmKwBgZcX
+fIPLsnmCgJKesTHpGi/SX4zEDyBZWVtwXVjyp9p9E6FoZAEP9tKxB9asfjuhyreM
+8WPytozz0z/p+hPZdQm2u0EBj1ygBUl297KJ7RmClmHSOrx1TbV+1UQM4+EkQm6G
+5vzfV4g8VwYjAoIBAQCETBHrL05E75vEITzBeLaaIfzUiZJIw0EZJvEHpLxhYGUU
+ctz7mKvG0szy6feTCLX7A3XSJZYTbuUbSo5F98xkB3BPPahqwjoEQJhFz4NFt2If
+6M8W8ef/sLbfw2LN0A9f5Os40RCXdfZM8AgYrJcmCRAMIVxlOBoWCC/6AJ6Oqno2
+mQojPJb+8IjGm8e0Du5iJa8rey2hbTyw1IzEC6p+4S8wfRC1FyObV9Z7y/MSDKyC
+Gw4nFS03Ch/oiaG5oTagvRBfEuyD9pnweh5hPiLV7iKLxR8G7dHmpRU4ZtXflTWm
+6P8dYdzro0aaKajqQh7uXnFQDQMzjRiClaizojt5AoIBAQC4Ynq8QyVpHXhcv2yF
+2/kU9S80MMJpd1EvG8kW1Yj2FRUMi73NjGwnUS4thh7eap18I4tf2MKkJvyrdHoF
+g3XQLSAq1uuBTw3J3Jx7MtX33SzHChlDadJkWzwVWjhyHp+Tg8U4fmzVpewZaUNZ
+andsOpNIKlsPvrFjM4wWE8J/MdnnaLYVMrWqW03+DIRGODVp8/JsltdQTY2Tn6rW
+RgToboqumpNqf4VrwWLFXBZBE807bBJnXc7TE0C+KbQS94zEFvvQgAMTlnB8Rjdi
+WnnYskZaMlsOVKkCWt+EcNFG1K07odDaEmbUAw4EWZfXNKlhwjyh7JP1ohX/hIP8
+emBHAoIBAEEF255xHPgb/SOtHLJPNDF9UdY/ZlQPm/GLwuBjt9f0Q3zoWz/ma6Pg
+gb1FglfGVbcyZUxYbUcCbzRg7zGCHULopyWvpq21bih0sfJVS5tMt69LT3Vq5UiQ
+SzD4fnjdoBfeLa3KQvFQbTykw+tDySCUuxTnPD9YGdMKK8daCDGvctaNhxIhklAY
+V1bshS2q//TEXieslCASfKC/xnIO66LiCiKixYxGeNOlOaa1e8ZDgQH2x98bkyVS
+5fIdkuWrHODyjCcR7tF4DeZUoRmOP5f78gcLdJ42VQWd5gcoQPQt8bZ++hCByArq
+QNDwzgfQn3qAxAzfZPo+P6ge/3izOMY=
+-----END PRIVATE KEY-----
diff --git a/certs/ca.srl b/certs/ca.srl
new file mode 100644
index 0000000000..b54a1f9c82
--- /dev/null
+++ b/certs/ca.srl
@@ -0,0 +1 @@
+245E2B62757EEB7E063ED4A7A8BAFF2B68F90D31
diff --git a/certs/client-keystore.p12 b/certs/client-keystore.p12
new file mode 100644
index 0000000000..40b1230f3a
Binary files /dev/null and b/certs/client-keystore.p12 differ
diff --git a/certs/client.crt b/certs/client.crt
new file mode 100644
index 0000000000..81247a5c94
--- /dev/null
+++ b/certs/client.crt
@@ -0,0 +1,26 @@
+-----BEGIN CERTIFICATE-----
+MIIEWDCCAkCgAwIBAgIUJF4rYnV+634GPtSnqLr/K2j5DTEwDQYJKoZIhvcNAQEL
+BQAwQTERMA8GA1UEAwwIQXhpczIgQ0ExFTATBgNVBAoMDEFwYWNoZSBBeGlzMjEV
+MBMGA1UECwwMSW9UIFNlcnZpY2VzMB4XDTI2MDQwNjE3NDkyOFoXDTI4MDQwNTE3
+NDkyOFowMjEZMBcGA1UEAwwQYXhpczItbWNwLWJyaWRnZTEVMBMGA1UECgwMQXBh
+Y2hlIEF4aXMyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAti2g8L8l
+4eIIkJscXGDqLA6NdCVgob1Us93nuFwhRiRPpkKii8OOEHn1jsqQMYKx2TAw8G+O
+ziIDrZZK4+Dm4hcv/6I3VifvTIZK5Ko1MrLoupA3eE65RiBPN9qUrzD4Py9YUMqg
+EbOJ790KKGmne2cUeGpirYtMG95O5BO3YbS9HrQp9xbtPTtJ+tStKvBMS7wISkOR
+w4vJ8HAjtORjgLnjlcZWzLuR+RP5yhsVjNqLNmHb1/XqZk54KJQJAsokc9CnENlL
+SGAW1F3ifzEo9Q3l6to763AwmQfzHp7lmWfw8jhjId+A3QoU6abPfjltYqf0BiFP
+IGy6hLj2UQVvSQIDAQABo1cwVTATBgNVHSUEDDAKBggrBgEFBQcDAjAdBgNVHQ4E
+FgQUeujyFgoS9pdQnT+0/rzI0XNWDK8wHwYDVR0jBBgwFoAU4Oa66Z/fBQIdWldv
+lvb+Jc8XWjMwDQYJKoZIhvcNAQELBQADggIBAEbGgs0Kc7UYkrd/mRjuzIbslGeA
+82Rjmknjedz88fC9KofDWI4fpMb/TEFgDMGWiQMUkLGYA4jhXsDMwQ/nYTK0Z5GU
++Fp29sN3tPz8ZVM00vo5IuxmSM5xU1JgMy2SCnWXu/5NJ9Ri1qipr+2532tZuJKq
+yz86du17QONcJ3WoNrtyBCurIW6TTHtQBgNQxl/M4bPHWW2WJ9bj1D26oQcM5tZj
+4LdhHndyON+W9TKY9zTIpjWu1eNJHfRGQhPgtO2e2L/mbFhiNmlq9lFQkFnbwrUy
+IhmaaHrqg96UMZsl8hQMlOLpIRuTbfzduCIkvCv1CZBCeOZhYxmh8049wrDCBasn
+1TiHZI9eqGQiF//72Qe97kqXN3UcaJYeRRnf1Jpm8Vm9Sn4U9N6Z+pTPb4Ts/MJA
+Wcg0NzEC/HxyqE0+0O7drTy0VXpzxmK41F2vwXMvqebafgsIwfK7LUgW1Q1hgW07
+Q/5MG06NHh5DTmvFFii74WMfAWW7R2gCnkSKLERFXHpPWqR6VCfDNeUhJ0xcKcCw
+Q4d9RK9NjsjMdNjFR1/gJl9vA+u96dkZIydyr0QAhWlzv4eAVYfaroGdwj7pJUiK
+7+HKjFPEhJR8pAGNP5H4x2yhH7xjz+PnItR1nYdLJn2CyFmRO2pNGRUgwpbDxUml
+X0i0DnRDjZjXqDjD
+-----END CERTIFICATE-----
diff --git a/certs/client.csr b/certs/client.csr
new file mode 100644
index 0000000000..fbe38e2e25
--- /dev/null
+++ b/certs/client.csr
@@ -0,0 +1,16 @@
+-----BEGIN CERTIFICATE REQUEST-----
+MIICdzCCAV8CAQAwMjEZMBcGA1UEAwwQYXhpczItbWNwLWJyaWRnZTEVMBMGA1UE
+CgwMQXBhY2hlIEF4aXMyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA
+ti2g8L8l4eIIkJscXGDqLA6NdCVgob1Us93nuFwhRiRPpkKii8OOEHn1jsqQMYKx
+2TAw8G+OziIDrZZK4+Dm4hcv/6I3VifvTIZK5Ko1MrLoupA3eE65RiBPN9qUrzD4
+Py9YUMqgEbOJ790KKGmne2cUeGpirYtMG95O5BO3YbS9HrQp9xbtPTtJ+tStKvBM
+S7wISkORw4vJ8HAjtORjgLnjlcZWzLuR+RP5yhsVjNqLNmHb1/XqZk54KJQJAsok
+c9CnENlLSGAW1F3ifzEo9Q3l6to763AwmQfzHp7lmWfw8jhjId+A3QoU6abPfjlt
+Yqf0BiFPIGy6hLj2UQVvSQIDAQABoAAwDQYJKoZIhvcNAQELBQADggEBAAyGI8AL
+HPRA2j21RdgFoRJeuwOXvH8kVISACiLXQHKYkMocBq9Kuy3uJ5Oh05tZUD5Swyh+
+idRMBRa7hWZegad+jXoLhQ579hl7gje1Dw3eLY+5HFrCwNrg+SZChJh0mneRiTrH
+kppW1I6IaXuQTO+GNonlFqmDzilV8P7VYikDia1zvL6oUVLaF5L7WbDxgj+C//DZ
+y3v7hZOoM99n0JphZUCuW2j2jHdkqzeFtNfTvc7Z+cy1mZq2IrDdgDRhVGJmfs9P
+bTpgWgu5jMHj243tkONSNtS2l1CdELCK8cbp7OlNzwzb+mkuwxzawPDgv57V771/
+aI5H+zunuwYpWRk=
+-----END CERTIFICATE REQUEST-----
diff --git a/certs/client.key b/certs/client.key
new file mode 100644
index 0000000000..78c1129c6a
--- /dev/null
+++ b/certs/client.key
@@ -0,0 +1,28 @@
+-----BEGIN PRIVATE KEY-----
+MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC2LaDwvyXh4giQ
+mxxcYOosDo10JWChvVSz3ee4XCFGJE+mQqKLw44QefWOypAxgrHZMDDwb47OIgOt
+lkrj4ObiFy//ojdWJ+9MhkrkqjUysui6kDd4TrlGIE832pSvMPg/L1hQyqARs4nv
+3Qooaad7ZxR4amKti0wb3k7kE7dhtL0etCn3Fu09O0n61K0q8ExLvAhKQ5HDi8nw
+cCO05GOAueOVxlbMu5H5E/nKGxWM2os2YdvX9epmTngolAkCyiRz0KcQ2UtIYBbU
+XeJ/MSj1DeXq2jvrcDCZB/MenuWZZ/DyOGMh34DdChTpps9+OW1ip/QGIU8gbLqE
+uPZRBW9JAgMBAAECggEAQmAhkVWzsbcvM7CwBqBw8ZhjxXuQ150p7VbehHdc0DeO
+pZ8FpjKb4jjtVRdMrh1WOzGpwxCCUWxnNqnZo2lf9eRI4rTxwHxQXetYAjRZqZ0x
+2jeNXlIggwJmmo0TOzl2WV8gqF8LLyfhC/nXJ55HHVkTRkRMq7pjAoxe5g6g9AHO
+ZVZiqhG1JRO9vO3clr60iCt5O0lD902aoYkF9V8V6VZBZioySTLbtQDASvYOM+Az
+lipyRWwkLI1N+p5HqgieADCYmDNFtvZhQePdjPAvYnCZynmfUKlLVRUkS78zhS3+
+v1OXQL2aYJpH6OuSN2wqopMnERjF6HY/as/SitLdmQKBgQDm7caGTCnn2nWKGl7h
+n2kWbOmQVcG1001I8X9bVNlA/6pjyGMx3yBmJB/vDtnbHT4WFW86kZrHZc66O8JZ
+Vo8MjccoOBkWT1pMCNmIdrKItRtEP4J0Df5GQ5Qxhllo0KukxLosF6jJVKYipRv+
+fbSzU0Bb+5GZ/NTZzeTjRBgrKwKBgQDJ9OycLe887ztPIDZlMbw5P7hQupuOGMDa
+P4HS9qSraK3HVFQFx2ezLWXjBfpDW1KHtxuqeZlH6w/vlhqAWJ/JQspL6aCaEiFt
+0XHJ46NabUbrOfZOXqZig5dK91+iLOtXw4r3i6xhZY+eb9GFYr3et/cRgmd+D9fc
+7dCQlqLFWwKBgQC/RvxFiRi83wq01Zr5r5zP4m6kCyRkgx1k6gPflqxNVnfAJt9j
+E7o2YH3C+b4h7Frc1+xFyw01VHKjd5RHg5cBgv4PpkfBXwEgMcRdcFP5QGnRYfmg
+P2b6tEcvrmSomQ9Tb0/17bL08JSb5b8GUQE3+CE7D2lO70kvD4gjZufN+QKBgQCJ
+v8pHeLlOaaqdfM49VaAZuFGilrWVRWL9OgX1/A8zbxHg/K7Wxj0AJL3zDFe366ku
+MoHnVEttl3JmK47l7g0GvMy43KCTljxA6HPhjagU/KY7uWw75ik81p6yHmqXdmYL
+la/KyvUH9brxCTny7fet2vLleXnXrTzCT19Lz8M0MwKBgFQOY/2Tc1Oqj+lM6Z2Y
+xDNxh1bRHvJFzVUdIMAypCtAWiWawUjG+Cb84Hx1O/icGR1fX8jQw9Oe+jAGGkID
+TiKlVK/uebE4glL9FlgLyzmNCafoVex1Lv889aY0pPWCTTQgSsakrpItHl8cxDrH
+irD9TczrDnFhdX3H0Z3vgV9y
+-----END PRIVATE KEY-----
diff --git a/certs/server-keystore.p12 b/certs/server-keystore.p12
new file mode 100644
index 0000000000..6d80bd8b6e
Binary files /dev/null and b/certs/server-keystore.p12 differ
diff --git a/certs/server.crt b/certs/server.crt
new file mode 100644
index 0000000000..ab4312bbb1
--- /dev/null
+++ b/certs/server.crt
@@ -0,0 +1,26 @@
+-----BEGIN CERTIFICATE-----
+MIIEbTCCAlWgAwIBAgIUJF4rYnV+634GPtSnqLr/K2j5DTAwDQYJKoZIhvcNAQEL
+BQAwQTERMA8GA1UEAwwIQXhpczIgQ0ExFTATBgNVBAoMDEFwYWNoZSBBeGlzMjEV
+MBMGA1UECwwMSW9UIFNlcnZpY2VzMB4XDTI2MDQwNjE3NDkyOFoXDTI4MDQwNTE3
+NDkyOFowKzESMBAGA1UEAwwJbG9jYWxob3N0MRUwEwYDVQQKDAxBcGFjaGUgQXhp
+czIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDLXWcvAA9ysJ7NPl4g
+EvZXLlAUWIVUc+qu+t4+zN2HxibAqJlh/lZcJRL6+qCOLZGpJeocstN5T3n7uiUV
+dLwd3VD20ZTCGqjkXlZiJTzoMwzDtPC5pbvSFkOcVld+bW9RZcKnhIDsCb1etxr1
+dNzaRtwtht9WtOEM/wgOUjt3HaBOqssIW5oaSXvsJBC9vwLALItBxNt/NnspNkOZ
+4zOdLgQ9LeRzmAL0dZLYfvhH4VQYROIsD1A30QPkZnsTsymTbRwVXbXwa1EY2pXr
+8DgqfShVMHZttjKZ19qxAdRU9uZwzm5iTv3BV4fctjgPPcFm3Dra5FwRPM87lay/
+7FCJAgMBAAGjczBxMBoGA1UdEQQTMBGCCWxvY2FsaG9zdIcEfwAAATATBgNVHSUE
+DDAKBggrBgEFBQcDATAdBgNVHQ4EFgQUB/8Icmj+ZvTXHjIQaufh2+1o9rIwHwYD
+VR0jBBgwFoAU4Oa66Z/fBQIdWldvlvb+Jc8XWjMwDQYJKoZIhvcNAQELBQADggIB
+AGpOTbN0PnR3n69g3Z3+GuAMU4HGre5GJ4FIKZQzQ0bS/bxwxFEQy/cD27KUzHsY
+KEqepwn9hyF0LDVgXTQ1KProrqrX27YW4Hs6mbgKWnHvkuL+a0vbeInTvE43Qm4R
+Fs1bB3jZGQSk3RFR1ZoRUG/fr2HWow+f6oDGxsr9K2E4EMXMIlH1zM+GEaYCvJVQ
+pOaU9LsVHkDEwDcY6dndx1UPoqBhaE1KauIE5eMHL9fj4BfpZ3wPgyFsA5ee2AQL
+9TKZjk5nQmXGgOLUrR5/93k3KV3EBnoWpkQNjchK0adeL8K+pyYgK2QjVOkW9+Or
+bz5S4LGq5Q889gYAKksM8xDYmxUm1A2V8MvFw4z6MD81PhU5ovvbEt+z4P3PxzpQ
+0ABmRiOGy2y5oArHa3nsg5KM56YVyDnWEgUaSufpRjXZOYW5FP4gmN2geQdrvf7a
+7WlOSdyW/N3p3hyFb7Sch4yVgKrsuWBPtoVOf8FnEj1V+CSXgX/h9E/AnyXQ1s9d
+FynxFAOyrQ4hR92c9KsG/GQqOslrsiMvQ3pmOA3TFzC0+ns6L6TO5eAI0krdDj+P
+SOc0nfiJRmnUoEqOY97SBBMMKvj0K0RHtoJPqOANZV//iBHKxR2AaRaj1a4gNK8p
+xkxg/MYBvcry2zax23cl8e7LDIWrR4qfvmarJcOJwfd4
+-----END CERTIFICATE-----
diff --git a/certs/server.csr b/certs/server.csr
new file mode 100644
index 0000000000..8fc8315d84
--- /dev/null
+++ b/certs/server.csr
@@ -0,0 +1,16 @@
+-----BEGIN CERTIFICATE REQUEST-----
+MIICcDCCAVgCAQAwKzESMBAGA1UEAwwJbG9jYWxob3N0MRUwEwYDVQQKDAxBcGFj
+aGUgQXhpczIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDLXWcvAA9y
+sJ7NPl4gEvZXLlAUWIVUc+qu+t4+zN2HxibAqJlh/lZcJRL6+qCOLZGpJeocstN5
+T3n7uiUVdLwd3VD20ZTCGqjkXlZiJTzoMwzDtPC5pbvSFkOcVld+bW9RZcKnhIDs
+Cb1etxr1dNzaRtwtht9WtOEM/wgOUjt3HaBOqssIW5oaSXvsJBC9vwLALItBxNt/
+NnspNkOZ4zOdLgQ9LeRzmAL0dZLYfvhH4VQYROIsD1A30QPkZnsTsymTbRwVXbXw
+a1EY2pXr8DgqfShVMHZttjKZ19qxAdRU9uZwzm5iTv3BV4fctjgPPcFm3Dra5FwR
+PM87lay/7FCJAgMBAAGgADANBgkqhkiG9w0BAQsFAAOCAQEAGG/lNyXocutSJt1D
+rn+axwPEB85P0/DoDkTBdYJKDQUKpGvAsLX9rA49uzrEaUocW38ahCyCyifAx8Mx
+h8+RCWj+aDFgGkocesRz+s0PMrfYvi2lTcuFATYwMbXmyoUDBfn5z8yMSUHo6wr8
+RqeoN1XZgmv77ks+lRGmjJIUJqmVj2IclLziwZpo21HSm09qxipIVZ47HWbym3zu
+F/JzGZb7y/+Hskr0KaoQ2JPIfdCddk7BOK49Y1fge2ew77dHZIX3JNi58ozvFNY2
+mxIpR5ia4hXu7ACByl1Rgvgy9Ly8nQj33db8yYE+R94BDkzSyFxT3BM0IrqSE7eh
+enbsdg==
+-----END CERTIFICATE REQUEST-----
diff --git a/certs/server.key b/certs/server.key
new file mode 100644
index 0000000000..8fcf6fd232
--- /dev/null
+++ b/certs/server.key
@@ -0,0 +1,28 @@
+-----BEGIN PRIVATE KEY-----
+MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDLXWcvAA9ysJ7N
+Pl4gEvZXLlAUWIVUc+qu+t4+zN2HxibAqJlh/lZcJRL6+qCOLZGpJeocstN5T3n7
+uiUVdLwd3VD20ZTCGqjkXlZiJTzoMwzDtPC5pbvSFkOcVld+bW9RZcKnhIDsCb1e
+txr1dNzaRtwtht9WtOEM/wgOUjt3HaBOqssIW5oaSXvsJBC9vwLALItBxNt/Nnsp
+NkOZ4zOdLgQ9LeRzmAL0dZLYfvhH4VQYROIsD1A30QPkZnsTsymTbRwVXbXwa1EY
+2pXr8DgqfShVMHZttjKZ19qxAdRU9uZwzm5iTv3BV4fctjgPPcFm3Dra5FwRPM87
+lay/7FCJAgMBAAECggEAKB5dQnWj1oeW0F0XIwMyozjA9f6PkP1MJSha6y8tncEe
+uH+aQK102nk64RXL0jiVpXWUFYTGuMYPxbPvaGfuy4JzXDm0u8UYH/MnXfXEKfeW
+M06Q9cLHBnc7b85NtOSAYyGs0LDQYSA7wkFjmVwsTIhRm86hZSDKS+7M50xcLE9r
+GAv/E2P7nM5/pU4Sb6jbRAmT1shFlZ7mV96XEQq5zn1iPvnhrnWN+Pe6UU53rpsi
+/THYT1g0aWJXuc5hjARosTt7hVkI+aC2iQyp5IAj85ID0yNYVuHe0lbisizPfL5w
+VJUPnYY9FxYEBp/1ASbpHw+myCidiX97XKGYLuSAzQKBgQDqLtlRxU9dSFKo2DON
+U6hhKUL4m0e6D9m6agbwnnQRmAbowVuh2jHOxZADP1TeiyoVM/M7W98xM9qboEu4
+reoKGsIuDiRBcWFQ0UKYLg204M+w0fiZyl9oIpDIubbP7cR9bz3s17hXWDab75gK
+HZv1MuacoiO4lUwUjybfZ/enTQKBgQDeT45n5NRPYLI9hq5W0X9Vo/vqczPTW4Wu
+lESTn9MhTZNS+nCu+Ons3rvqBKNB0Ureb3o/iIYFoQmY2XC2da/Dicq9YYUjKT5I
+LmIhDaMP4SKEPxXLhAZZ1atFhrIK6+TGTByfaML7WYxWwP889KiFA7vr6fygVWSI
+PRVuBw+ILQKBgAd1HHiNJvzae79iuymJ+3e0n6xZDYywSoe0Lqpk8V9KDxZEag2a
+bDGgeviPgL1hgyKPt/Qw9ceUVibUkPS9nRFbTsm2q5Ll8Gppb4x3EvqqmhKQbTFA
+j486Yo/x0g+HC9XOwBMVv4oQhhSrKZVQ4hGJ4Gwmgaq0HmsdL+i3X9yVAoGBANeo
+paTzv2Ihk8dL1+Qw5y3VHpSZnTT0HAL3om7zJIWyE7DzckzK+2Llz7V9OkKnHdIa
+oqTvc9QSHJVCmqzmDdPK3/pHmDg70keDd35JFF5bMHjKGgKL2P1c4gFYYW9m10/m
+lf2uSzg57oJaR0CCttgSf0KkgoWnURc46okKIG8hAoGATQfgc8uEwtCyqk5bXmyK
+7CoP5oFPCYzN7iIyvsGMx1tjEAWBirmElza6tt9L+X2z4hxPitXFSX2nPYUbGO53
+Kzk1I4SFNJ7Zhq87z2VuvAyS3godeEqJxc4J+oBb5iP5/ROevaImIvzEFQeofPT3
+qLhOe0faQoWFraO34QWEtkQ=
+-----END PRIVATE KEY-----
diff --git a/modules/mcp-bridge/pom.xml b/modules/mcp-bridge/pom.xml
new file mode 100644
index 0000000000..ef19382743
--- /dev/null
+++ b/modules/mcp-bridge/pom.xml
@@ -0,0 +1,113 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ Licensed to the Apache Software Foundation (ASF) under one
+ ~ or more contributor license agreements. See the NOTICE file
+ ~ distributed with this work for additional information
+ ~ regarding copyright ownership. The ASF licenses this file
+ ~ to you under the Apache License, Version 2.0 (the
+ ~ "License"); you may not use this file except in compliance
+ ~ with the License. You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied. See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.apache.axis2</groupId>
+ <artifactId>axis2</artifactId>
+ <version>2.0.1-SNAPSHOT</version>
+ <relativePath>../../pom.xml</relativePath>
+ </parent>
+
+ <artifactId>axis2-mcp-bridge</artifactId>
+ <packaging>jar</packaging>
+
+ <name>Apache Axis2 - MCP Bridge</name>
+ <description>
+ Stdio MCP (Model Context Protocol) bridge for Apache Axis2. Fetches the
+ /openapi-mcp.json tool catalog from a running Axis2 deployment and exposes
+ those operations as MCP tools to Claude Desktop and other MCP clients.
+ Runs as a subprocess launched by an MCP client; communicates via
+ newline-delimited JSON-RPC 2.0 on stdin/stdout.
+ </description>
+
+ <properties>
+ <jackson.version>2.21.1</jackson.version>
+ </properties>
+
+ <dependencies>
+ <!-- JSON parsing — Apache 2.0 -->
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-databind</artifactId>
+ <version>${jackson.version}</version>
+ </dependency>
+
+ <!-- Test -->
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <source>17</source>
+ <target>17</target>
+ </configuration>
+ </plugin>
+
+ <!-- Build a self-contained executable JAR for use as an MCP stdio server. -->
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-shade-plugin</artifactId>
+ <version>3.6.0</version>
+ <executions>
+ <execution>
+ <phase>package</phase>
+ <goals>
+ <goal>shade</goal>
+ </goals>
+ <configuration>
+ <createDependencyReducedPom>false</createDependencyReducedPom>
+ <shadedArtifactAttached>true</shadedArtifactAttached>
+ <shadedClassifierName>exe</shadedClassifierName>
+ <transformers>
+ <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
+ <mainClass>org.apache.axis2.mcp.bridge.McpBridgeMain</mainClass>
+ </transformer>
+ <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
+ </transformers>
+ <filters>
+ <filter>
+ <artifact>*:*</artifact>
+ <excludes>
+ <exclude>META-INF/*.SF</exclude>
+ <exclude>META-INF/*.DSA</exclude>
+ <exclude>META-INF/*.RSA</exclude>
+ </excludes>
+ </filter>
+ </filters>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+</project>
diff --git a/modules/mcp-bridge/src/main/java/org/apache/axis2/mcp/bridge/McpBridgeMain.java b/modules/mcp-bridge/src/main/java/org/apache/axis2/mcp/bridge/McpBridgeMain.java
new file mode 100644
index 0000000000..f78d7103cc
--- /dev/null
+++ b/modules/mcp-bridge/src/main/java/org/apache/axis2/mcp/bridge/McpBridgeMain.java
@@ -0,0 +1,143 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.axis2.mcp.bridge;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManagerFactory;
+import java.io.FileInputStream;
+import java.security.KeyStore;
+
+/**
+ * Entry point for the Axis2 MCP bridge.
+ *
+ * <p>Usage (mTLS — required):
+ * <pre>
+ * java -jar axis2-mcp-bridge-exe.jar \
+ * --base-url https://localhost:8443/axis2-json-api \
+ * --keystore /path/to/client-keystore.p12 \
+ * --truststore /path/to/ca-truststore.p12
+ * </pre>
+ *
+ * <p>The keystore holds the client certificate and private key (PKCS12).
+ * The truststore holds the CA certificate used to verify the server.
+ * Both use the password {@code changeit} by default; override with
+ * {@code --keystore-password} and {@code --truststore-password}.
+ *
+ * <p>Claude Desktop configuration ({@code ~/.config/claude/claude_desktop_config.json}):
+ * <pre>
+ * {
+ * "mcpServers": {
+ * "axis2-demo": {
+ * "command": "java",
+ * "args": ["-jar", "/path/to/axis2-mcp-bridge-exe.jar",
+ * "--base-url", "https://localhost:8443/axis2-json-api",
+ * "--keystore", "/path/to/client-keystore.p12",
+ * "--truststore", "/path/to/ca-truststore.p12"]
+ * }
+ * }
+ * }
+ * </pre>
+ *
+ * <p>All diagnostic output is written to stderr so it does not corrupt the
+ * MCP protocol stream on stdout.
+ */
+public class McpBridgeMain {
+
+ public static void main(String[] args) {
+ String baseUrl = parseArg(args, "--base-url");
+ String keystorePath = parseArg(args, "--keystore");
+ String truststorePath = parseArg(args, "--truststore");
+ String keystorePass = parseArgOrDefault(args, "--keystore-password", "changeit");
+ String truststorePass = parseArgOrDefault(args, "--truststore-password", "changeit");
+
+ if (baseUrl == null || keystorePath == null || truststorePath == null) {
+ System.err.println("Usage: axis2-mcp-bridge");
+ System.err.println(" --base-url https://localhost:8443/axis2-json-api");
+ System.err.println(" --keystore /path/to/client-keystore.p12");
+ System.err.println(" --truststore /path/to/ca-truststore.p12");
+ System.err.println(" [--keystore-password changeit]");
+ System.err.println(" [--truststore-password changeit]");
+ System.exit(1);
+ }
+
+ System.err.println("[axis2-mcp-bridge] Starting — base-url: " + baseUrl);
+
+ ObjectMapper mapper = new ObjectMapper();
+
+ try {
+ SSLContext sslContext = buildSslContext(
+ keystorePath, keystorePass.toCharArray(),
+ truststorePath, truststorePass.toCharArray());
+
+ ToolRegistry registry = new ToolRegistry(baseUrl, mapper, sslContext);
+ registry.load();
+
+ McpStdioServer server = new McpStdioServer(baseUrl, registry, mapper, sslContext);
+ server.run();
+
+ } catch (Exception e) {
+ System.err.println("[axis2-mcp-bridge] Fatal: " + e.getMessage());
+ e.printStackTrace(System.err);
+ System.exit(1);
+ }
+ }
+
+ /**
+ * Builds an {@link SSLContext} for mTLS from PKCS12 keystore and truststore files.
+ */
+ static SSLContext buildSslContext(String keystorePath, char[] keystorePass,
+ String truststorePath, char[] truststorePass)
+ throws Exception {
+ // Client certificate + private key
+ KeyStore keyStore = KeyStore.getInstance("PKCS12");
+ try (FileInputStream fis = new FileInputStream(keystorePath)) {
+ keyStore.load(fis, keystorePass);
+ }
+ KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
+ kmf.init(keyStore, keystorePass);
+
+ // CA certificate for server verification
+ KeyStore trustStore = KeyStore.getInstance("PKCS12");
+ try (FileInputStream fis = new FileInputStream(truststorePath)) {
+ trustStore.load(fis, truststorePass);
+ }
+ TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
+ tmf.init(trustStore);
+
+ SSLContext sslContext = SSLContext.getInstance("TLS");
+ sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
+ System.err.println("[axis2-mcp-bridge] mTLS SSLContext initialized");
+ return sslContext;
+ }
+
+ private static String parseArg(String[] args, String key) {
+ for (int i = 0; i < args.length - 1; i++) {
+ if (key.equals(args[i])) return args[i + 1];
+ }
+ return null;
+ }
+
+ private static String parseArgOrDefault(String[] args, String key, String defaultValue) {
+ String v = parseArg(args, key);
+ return v != null ? v : defaultValue;
+ }
+}
diff --git a/modules/mcp-bridge/src/main/java/org/apache/axis2/mcp/bridge/McpStdioServer.java b/modules/mcp-bridge/src/main/java/org/apache/axis2/mcp/bridge/McpStdioServer.java
new file mode 100644
index 0000000000..c378661900
--- /dev/null
+++ b/modules/mcp-bridge/src/main/java/org/apache/axis2/mcp/bridge/McpStdioServer.java
@@ -0,0 +1,247 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.axis2.mcp.bridge;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
+import javax.net.ssl.SSLContext;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.PrintStream;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+
+/**
+ * MCP stdio server: reads JSON-RPC 2.0 requests from stdin, writes responses
+ * to stdout. All diagnostic output goes to stderr so it does not pollute the
+ * MCP protocol stream.
+ *
+ * <p>Implements the three methods required by the MCP specification:
+ * <ul>
+ * <li>{@code initialize} — returns server capabilities and protocol version</li>
+ * <li>{@code tools/list} — returns the Axis2 tool catalog</li>
+ * <li>{@code tools/call} — proxies the call to the Axis2 HTTP endpoint</li>
+ * </ul>
+ *
+ * <p>Notifications (messages without an {@code id} field) are silently consumed
+ * with no response, as required by JSON-RPC 2.0.
+ */
+public class McpStdioServer {
+
+ private static final String PROTOCOL_VERSION = "2024-11-05";
+ private static final String SERVER_NAME = "axis2-mcp-bridge";
+ private static final String SERVER_VERSION = "2.0.1-SNAPSHOT";
+
+ private final String baseUrl;
+ private final ToolRegistry registry;
+ private final ObjectMapper mapper;
+ private final HttpClient httpClient;
+ private final PrintStream out;
+
+ public McpStdioServer(String baseUrl, ToolRegistry registry, ObjectMapper mapper, SSLContext sslContext) {
+ this.baseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl;
+ this.registry = registry;
+ this.mapper = mapper;
+ HttpClient.Builder builder = HttpClient.newBuilder()
+ .connectTimeout(Duration.ofSeconds(10));
+ if (sslContext != null) {
+ builder.sslContext(sslContext);
+ }
+ this.httpClient = builder.build();
+ // stdout must be raw bytes in UTF-8; replace the default PrintStream
+ this.out = new PrintStream(System.out, true, StandardCharsets.UTF_8);
+ }
+
+ /**
+ * Blocking read loop. Returns when stdin is closed (client disconnected).
+ */
+ public void run() throws IOException {
+ BufferedReader reader = new BufferedReader(
+ new InputStreamReader(System.in, StandardCharsets.UTF_8));
+
+ String line;
+ while ((line = reader.readLine()) != null) {
+ line = line.trim();
+ if (line.isEmpty()) continue;
+
+ try {
+ processLine(line);
+ } catch (Exception e) {
+ System.err.println("[axis2-mcp-bridge] Unhandled error: " + e.getMessage());
+ }
+ }
+ System.err.println("[axis2-mcp-bridge] stdin closed — exiting");
+ }
+
+ private void processLine(String line) throws Exception {
+ JsonNode request;
+ try {
+ request = mapper.readTree(line);
+ } catch (Exception e) {
+ // Cannot parse — write parse error with null id per JSON-RPC 2.0 spec
+ writeError(mapper.nullNode(), -32700, "Parse error: " + e.getMessage());
+ return;
+ }
+
+ String method = request.path("method").asText("");
+ JsonNode id = request.get("id");
+
+ // Notifications have no "id" field — consume silently, no response
+ if (id == null) {
+ System.err.println("[axis2-mcp-bridge] Notification: " + method);
+ return;
+ }
+
+ JsonNode params = request.path("params");
+ System.err.println("[axis2-mcp-bridge] Request id=" + id + " method=" + method);
+
+ switch (method) {
+ case "initialize":
+ writeSuccess(id, buildInitializeResult(params));
+ break;
+ case "tools/list":
+ writeSuccess(id, buildToolsListResult());
+ break;
+ case "tools/call":
+ writeSuccess(id, buildToolsCallResult(params));
+ break;
+ default:
+ writeError(id, -32601, "Method not found: " + method);
+ }
+ }
+
+ // ── initialize ──────────────────────────────────────────────────────────
+
+ private ObjectNode buildInitializeResult(JsonNode params) {
+ ObjectNode result = mapper.createObjectNode();
+ result.put("protocolVersion", PROTOCOL_VERSION);
+
+ // capabilities.tools presence signals this server supports the tools feature
+ ObjectNode capabilities = result.putObject("capabilities");
+ capabilities.putObject("tools");
+
+ ObjectNode serverInfo = result.putObject("serverInfo");
+ serverInfo.put("name", SERVER_NAME);
+ serverInfo.put("version", SERVER_VERSION);
+
+ return result;
+ }
+
+ // ── tools/list ──────────────────────────────────────────────────────────
+
+ private ObjectNode buildToolsListResult() {
+ ArrayNode toolsArray = mapper.createArrayNode();
+ for (McpTool tool : registry.getTools()) {
+ ObjectNode toolNode = mapper.createObjectNode();
+ toolNode.put("name", tool.getName());
+ toolNode.put("description", tool.getDescription());
+ toolNode.set("inputSchema", tool.getInputSchema());
+ toolsArray.add(toolNode);
+ }
+ ObjectNode result = mapper.createObjectNode();
+ result.set("tools", toolsArray);
+ return result;
+ }
+
+ // ── tools/call ──────────────────────────────────────────────────────────
+
+ private ObjectNode buildToolsCallResult(JsonNode params) throws IOException, InterruptedException {
+ String toolName = params.path("name").asText(null);
+ if (toolName == null || toolName.isEmpty()) {
+ throw new IllegalArgumentException("tools/call missing required param 'name'");
+ }
+
+ McpTool tool = registry.getTool(toolName);
+ if (tool == null) {
+ throw new IllegalArgumentException("Unknown tool: " + toolName);
+ }
+
+ JsonNode arguments = params.path("arguments");
+ String responseBody = callAxis2(tool, arguments);
+
+ // Return response as MCP text content
+ ObjectNode result = mapper.createObjectNode();
+ ArrayNode content = result.putArray("content");
+ ObjectNode textItem = content.addObject();
+ textItem.put("type", "text");
+ textItem.put("text", responseBody);
+ return result;
+ }
+
+ /**
+ * POST to the Axis2 endpoint. Wraps MCP arguments in the Axis2 JSON-RPC
+ * request envelope: {@code {operationName: [arguments]}}.
+ */
+ private String callAxis2(McpTool tool, JsonNode arguments) throws IOException, InterruptedException {
+ String url = baseUrl + tool.getPath();
+
+ // Axis2 JSON-RPC envelope: {"operationName": [arguments]}
+ ObjectNode body = mapper.createObjectNode();
+ ArrayNode argArray = body.putArray(tool.getName());
+ argArray.add(arguments.isNull() ? mapper.createObjectNode() : arguments);
+
+ String requestBody = mapper.writeValueAsString(body);
+ System.err.println("[axis2-mcp-bridge] Calling: POST " + url);
+ System.err.println("[axis2-mcp-bridge] Body: " + requestBody);
+
+ HttpRequest httpRequest = HttpRequest.newBuilder()
+ .uri(URI.create(url))
+ .header("Content-Type", "application/json")
+ .timeout(Duration.ofSeconds(60))
+ .POST(HttpRequest.BodyPublishers.ofString(requestBody, StandardCharsets.UTF_8))
+ .build();
+
+ HttpResponse<String> response = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
+ System.err.println("[axis2-mcp-bridge] Response: HTTP " + response.statusCode());
+ return response.body();
+ }
+
+ // ── JSON-RPC 2.0 response helpers ───────────────────────────────────────
+
+ private void writeSuccess(JsonNode id, JsonNode result) throws IOException {
+ ObjectNode envelope = mapper.createObjectNode();
+ envelope.put("jsonrpc", "2.0");
+ envelope.set("id", id);
+ envelope.set("result", result);
+ writeLine(mapper.writeValueAsString(envelope));
+ }
+
+ private void writeError(JsonNode id, int code, String message) throws IOException {
+ ObjectNode envelope = mapper.createObjectNode();
+ envelope.put("jsonrpc", "2.0");
+ envelope.set("id", id);
+ ObjectNode error = envelope.putObject("error");
+ error.put("code", code);
+ error.put("message", message);
+ writeLine(mapper.writeValueAsString(envelope));
+ }
+
+ private void writeLine(String json) {
+ out.println(json);
+ out.flush();
+ }
+}
diff --git a/modules/mcp-bridge/src/main/java/org/apache/axis2/mcp/bridge/McpTool.java b/modules/mcp-bridge/src/main/java/org/apache/axis2/mcp/bridge/McpTool.java
new file mode 100644
index 0000000000..e44cce3a79
--- /dev/null
+++ b/modules/mcp-bridge/src/main/java/org/apache/axis2/mcp/bridge/McpTool.java
@@ -0,0 +1,60 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.axis2.mcp.bridge;
+
+import com.fasterxml.jackson.databind.JsonNode;
+
+/**
+ * Represents one MCP tool entry parsed from {@code /openapi-mcp.json}.
+ *
+ * <p>Fields mirror the tool catalog format produced by {@code axis2-openapi}:
+ * <pre>
+ * {
+ * "name": "processBigDataSet",
+ * "description": "BigDataH2Service: processBigDataSet",
+ * "inputSchema": { "type": "object", "properties": {}, "required": [] },
+ * "endpoint": "POST /services/BigDataH2Service/processBigDataSet"
+ * }
+ * </pre>
+ */
+public class McpTool {
+
+ private final String name;
+ private final String description;
+ private final JsonNode inputSchema;
+ /** Raw endpoint string, e.g. {@code "POST /services/Svc/op"}. */
+ private final String endpoint;
+ /** Just the path portion, e.g. {@code "/services/Svc/op"}. */
+ private final String path;
+
+ public McpTool(String name, String description, JsonNode inputSchema, String endpoint) {
+ this.name = name;
+ this.description = description != null ? description : name;
+ this.inputSchema = inputSchema;
+ this.endpoint = endpoint;
+ // Strip the HTTP method prefix to get just the path
+ this.path = endpoint.contains(" ") ? endpoint.substring(endpoint.indexOf(' ') + 1) : endpoint;
+ }
+
+ public String getName() { return name; }
+ public String getDescription() { return description; }
+ public JsonNode getInputSchema() { return inputSchema; }
+ public String getEndpoint() { return endpoint; }
+ public String getPath() { return path; }
+}
diff --git a/modules/mcp-bridge/src/main/java/org/apache/axis2/mcp/bridge/ToolRegistry.java b/modules/mcp-bridge/src/main/java/org/apache/axis2/mcp/bridge/ToolRegistry.java
new file mode 100644
index 0000000000..4f2203a0b0
--- /dev/null
+++ b/modules/mcp-bridge/src/main/java/org/apache/axis2/mcp/bridge/ToolRegistry.java
@@ -0,0 +1,119 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.axis2.mcp.bridge;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import javax.net.ssl.SSLContext;
+import java.io.IOException;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Fetches the MCP tool catalog from {@code {baseUrl}/openapi-mcp.json} and
+ * makes it available for {@link McpStdioServer}.
+ *
+ * <p>The catalog endpoint is produced by the {@code axis2-openapi} module.
+ * It is fetched once at startup; restart the bridge to pick up newly deployed
+ * services.
+ */
+public class ToolRegistry {
+
+ private final String baseUrl;
+ private final ObjectMapper mapper;
+ private final HttpClient httpClient;
+
+ private List<McpTool> tools = Collections.emptyList();
+ private Map<String, McpTool> toolMap = Collections.emptyMap();
+
+ public ToolRegistry(String baseUrl, ObjectMapper mapper, SSLContext sslContext) {
+ this.baseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl;
+ this.mapper = mapper;
+ HttpClient.Builder builder = HttpClient.newBuilder()
+ .connectTimeout(Duration.ofSeconds(10));
+ if (sslContext != null) {
+ builder.sslContext(sslContext);
+ }
+ this.httpClient = builder.build();
+ }
+
+ /**
+ * Fetches {@code /openapi-mcp.json} and builds the tool registry.
+ * Logs to stderr; does not throw on partial failure (empty catalog is valid).
+ */
+ public void load() throws IOException, InterruptedException {
+ String catalogUrl = baseUrl + "/openapi-mcp.json";
+ System.err.println("[axis2-mcp-bridge] Loading tool catalog from: " + catalogUrl);
+
+ HttpRequest request = HttpRequest.newBuilder()
+ .uri(URI.create(catalogUrl))
+ .header("Accept", "application/json")
+ .timeout(Duration.ofSeconds(15))
+ .GET()
+ .build();
+
+ HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
+
+ if (response.statusCode() != 200) {
+ throw new IOException("Tool catalog fetch failed: HTTP " + response.statusCode()
+ + " from " + catalogUrl);
+ }
+
+ JsonNode root = mapper.readTree(response.body());
+ JsonNode toolsNode = root.path("tools");
+
+ if (!toolsNode.isArray()) {
+ System.err.println("[axis2-mcp-bridge] Warning: 'tools' array not found in catalog — no tools registered");
+ return;
+ }
+
+ List<McpTool> loaded = new ArrayList<>();
+ Map<String, McpTool> map = new LinkedHashMap<>();
+
+ for (JsonNode toolNode : toolsNode) {
+ String name = toolNode.path("name").asText(null);
+ if (name == null || name.isEmpty()) continue;
+
+ String description = toolNode.path("description").asText(name);
+ JsonNode inputSchema = toolNode.path("inputSchema");
+ String endpoint = toolNode.path("endpoint").asText("");
+
+ McpTool tool = new McpTool(name, description, inputSchema, endpoint);
+ loaded.add(tool);
+ map.put(name, tool);
+ }
+
+ this.tools = Collections.unmodifiableList(loaded);
+ this.toolMap = Collections.unmodifiableMap(map);
+ System.err.println("[axis2-mcp-bridge] Loaded " + tools.size() + " tool(s): " + map.keySet());
+ }
+
+ public List<McpTool> getTools() { return tools; }
+
+ public McpTool getTool(String name) { return toolMap.get(name); }
+}
diff --git a/modules/mcp-bridge/src/test/java/org/apache/axis2/mcp/bridge/McpBridgeMainTest.java b/modules/mcp-bridge/src/test/java/org/apache/axis2/mcp/bridge/McpBridgeMainTest.java
new file mode 100644
index 0000000000..82f8b5dbf7
--- /dev/null
+++ b/modules/mcp-bridge/src/test/java/org/apache/axis2/mcp/bridge/McpBridgeMainTest.java
@@ -0,0 +1,187 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.axis2.mcp.bridge;
+
+import junit.framework.TestCase;
+
+import javax.net.ssl.SSLContext;
+import java.io.File;
+import java.lang.reflect.Method;
+
+/**
+ * Unit tests for {@link McpBridgeMain}.
+ *
+ * <p>Tests argument parsing (private static methods accessed via reflection)
+ * and, when the project certificate files are present, {@code buildSslContext}.
+ */
+public class McpBridgeMainTest extends TestCase {
+
+ // ── argument parsing ─────────────────────────────────────────────────────
+
+ private static String callParseArg(String[] args, String key) throws Exception {
+ Method m = McpBridgeMain.class.getDeclaredMethod("parseArg", String[].class, String.class);
+ m.setAccessible(true);
+ return (String) m.invoke(null, args, key);
+ }
+
+ private static String callParseArgOrDefault(String[] args, String key, String def) throws Exception {
+ Method m = McpBridgeMain.class.getDeclaredMethod(
+ "parseArgOrDefault", String[].class, String.class, String.class);
+ m.setAccessible(true);
+ return (String) m.invoke(null, args, key, def);
+ }
+
+ public void testParseArgReturnsValueWhenKeyPresent() throws Exception {
+ String[] args = {"--base-url", "https://localhost:8443/axis2-json-api",
+ "--keystore", "/path/to/ks.p12"};
+ assertEquals("https://localhost:8443/axis2-json-api",
+ callParseArg(args, "--base-url"));
+ assertEquals("/path/to/ks.p12",
+ callParseArg(args, "--keystore"));
+ }
+
+ public void testParseArgReturnsNullWhenKeyAbsent() throws Exception {
+ String[] args = {"--base-url", "https://localhost:8443/axis2-json-api"};
+ assertNull(callParseArg(args, "--truststore"));
+ }
+
+ public void testParseArgReturnsNullForEmptyArgs() throws Exception {
+ assertNull(callParseArg(new String[]{}, "--base-url"));
+ }
+
+ public void testParseArgIgnoresKeyAtLastPosition() throws Exception {
+ // Key at last index has no following value — must not throw AIOOBE
+ String[] args = {"--other", "val", "--base-url"};
+ assertNull(callParseArg(args, "--base-url"));
+ }
+
+ public void testParseArgReturnsFirstMatchOnly() throws Exception {
+ // If a key appears twice, the first value wins (spec: first match)
+ String[] args = {"--base-url", "first", "--base-url", "second"};
+ assertEquals("first", callParseArg(args, "--base-url"));
+ }
+
+ public void testParseArgOrDefaultReturnsValueWhenKeyPresent() throws Exception {
+ String[] args = {"--keystore-password", "mySecret"};
+ assertEquals("mySecret",
+ callParseArgOrDefault(args, "--keystore-password", "changeit"));
+ }
+
+ public void testParseArgOrDefaultReturnsDefaultWhenKeyAbsent() throws Exception {
+ assertEquals("changeit",
+ callParseArgOrDefault(new String[]{}, "--keystore-password", "changeit"));
+ }
+
+ public void testParseArgOrDefaultReturnsDefaultWhenEmpty() throws Exception {
+ assertEquals("default",
+ callParseArgOrDefault(new String[]{}, "--missing", "default"));
+ }
+
+ public void testParseArgWithAdjacentOtherArgs() throws Exception {
+ String[] args = {
+ "--unrelated", "value",
+ "--keystore", "/certs/client.p12",
+ "--truststore", "/certs/ca.p12"
+ };
+ assertEquals("/certs/client.p12", callParseArg(args, "--keystore"));
+ assertEquals("/certs/ca.p12", callParseArg(args, "--truststore"));
+ assertNull(callParseArg(args, "--base-url"));
+ }
+
+ // ── buildSslContext with real cert files ──────────────────────────────────
+
+ /**
+ * Verifies that {@code buildSslContext} successfully initialises an
+ * {@link SSLContext} from the PKCS12 files created during project setup.
+ *
+ * <p>The test is skipped (passes vacuously) when the cert directory does
+ * not exist, so it does not break CI environments that don't have the certs.
+ */
+ public void testBuildSslContextWithProjectCerts() throws Exception {
+ // Locate the certs directory relative to the mcp-bridge module
+ File certsDir = new File("../../certs");
+ if (!certsDir.exists()) {
+ // Try from the repo root
+ certsDir = new File("certs");
+ }
+ if (!certsDir.exists()) {
+ System.out.println("SKIPPED testBuildSslContextWithProjectCerts: " +
+ "certs/ directory not found — run from repo root");
+ return;
+ }
+
+ File serverKs = new File(certsDir, "server-keystore.p12");
+ File caTs = new File(certsDir, "ca-truststore.p12");
+ File clientKs = new File(certsDir, "client-keystore.p12");
+
+ if (!serverKs.exists() || !caTs.exists() || !clientKs.exists()) {
+ System.out.println("SKIPPED testBuildSslContextWithProjectCerts: " +
+ "one or more keystore files missing in " + certsDir.getAbsolutePath());
+ return;
+ }
+
+ // Test server-side context (server keystore + CA truststore)
+ SSLContext serverCtx = McpBridgeMain.buildSslContext(
+ serverKs.getAbsolutePath(), "changeit".toCharArray(),
+ caTs.getAbsolutePath(), "changeit".toCharArray());
+ assertNotNull("Server SSLContext must not be null", serverCtx);
+ assertEquals("TLS", serverCtx.getProtocol());
+
+ // Test client-side context (client keystore + CA truststore)
+ SSLContext clientCtx = McpBridgeMain.buildSslContext(
+ clientKs.getAbsolutePath(), "changeit".toCharArray(),
+ caTs.getAbsolutePath(), "changeit".toCharArray());
+ assertNotNull("Client SSLContext must not be null", clientCtx);
+ assertEquals("TLS", clientCtx.getProtocol());
+ }
+
+ public void testBuildSslContextThrowsForNonExistentKeystore() {
+ try {
+ McpBridgeMain.buildSslContext(
+ "/does/not/exist.p12", "changeit".toCharArray(),
+ "/does/not/exist-trust.p12", "changeit".toCharArray());
+ fail("Expected an exception for a non-existent keystore file");
+ } catch (Exception e) {
+ // Any exception is acceptable — FileNotFoundException, KeyStoreException, etc.
+ assertNotNull("Exception must have a message", e.getMessage() != null || e.getCause() != null);
+ }
+ }
+
+ public void testBuildSslContextThrowsForWrongPassword() throws Exception {
+ File certsDir = new File("../../certs");
+ if (!certsDir.exists()) certsDir = new File("certs");
+ File clientKs = new File(certsDir, "client-keystore.p12");
+ File caTs = new File(certsDir, "ca-truststore.p12");
+
+ if (!clientKs.exists() || !caTs.exists()) {
+ System.out.println("SKIPPED testBuildSslContextThrowsForWrongPassword: " +
+ "cert files not found");
+ return;
+ }
+
+ try {
+ McpBridgeMain.buildSslContext(
+ clientKs.getAbsolutePath(), "wrongpassword".toCharArray(),
+ caTs.getAbsolutePath(), "changeit".toCharArray());
+ fail("Expected an exception for wrong keystore password");
+ } catch (Exception e) {
+ // Expected — wrong password causes load() to throw
+ }
+ }
+}
diff --git a/modules/mcp-bridge/src/test/java/org/apache/axis2/mcp/bridge/McpStdioServerTest.java b/modules/mcp-bridge/src/test/java/org/apache/axis2/mcp/bridge/McpStdioServerTest.java
new file mode 100644
index 0000000000..f5866b9c28
--- /dev/null
+++ b/modules/mcp-bridge/src/test/java/org/apache/axis2/mcp/bridge/McpStdioServerTest.java
@@ -0,0 +1,429 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.axis2.mcp.bridge;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import junit.framework.TestCase;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.io.PrintStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Unit tests for {@link McpStdioServer}.
+ *
+ * <p>Each test redirects {@code System.in} / {@code System.out} around the
+ * server run loop so the JSON-RPC 2.0 responses can be captured and verified
+ * without any real HTTP or TLS infrastructure.
+ *
+ * <p>A {@link StubToolRegistry} inner class overrides {@link ToolRegistry}'s
+ * getters to inject known tools without calling the HTTP {@code load()} method.
+ */
+public class McpStdioServerTest extends TestCase {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ // ── helpers ─────────────────────────────────────────────────────────────
+
+ /**
+ * Runs the server with the given newline-delimited JSON-RPC input lines and
+ * returns all stdout output as a single string (lines separated by newlines).
+ */
+ private String runServer(StubToolRegistry registry, String... inputLines) throws Exception {
+ String inputData = String.join("\n", inputLines) + "\n";
+
+ PrintStream savedOut = System.out;
+ InputStream savedIn = System.in;
+ try {
+ ByteArrayOutputStream captured = new ByteArrayOutputStream();
+ // Replace System.out BEFORE constructing the server so the
+ // server's internal PrintStream wraps our capture buffer.
+ System.setOut(new PrintStream(captured, true, StandardCharsets.UTF_8));
+ System.setIn(new ByteArrayInputStream(
+ inputData.getBytes(StandardCharsets.UTF_8)));
+
+ McpStdioServer server = new McpStdioServer(
+ "https://localhost:8443/axis2-json-api", registry, MAPPER, null);
+ server.run();
+
+ return captured.toString(StandardCharsets.UTF_8).trim();
+ } finally {
+ System.setOut(savedOut);
+ System.setIn(savedIn);
+ }
+ }
+
+ /** Parses a single-line JSON-RPC response. Fails the test if output has multiple lines. */
+ private JsonNode parseSingleResponse(String output) throws Exception {
+ String[] lines = output.split("\n");
+ // Filter out blank lines
+ String responseLine = null;
+ for (String line : lines) {
+ if (!line.trim().isEmpty()) {
+ assertNull("Expected single response line but got multiple non-empty lines", responseLine);
+ responseLine = line.trim();
+ }
+ }
+ assertNotNull("Expected at least one response line", responseLine);
+ return MAPPER.readTree(responseLine);
+ }
+
+ // ── initialize ──────────────────────────────────────────────────────────
+
+ public void testInitializeReturnsProtocolVersion() throws Exception {
+ String output = runServer(new StubToolRegistry(),
+ "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\"," +
+ "\"params\":{\"protocolVersion\":\"2024-11-05\",\"capabilities\":{}," +
+ "\"clientInfo\":{\"name\":\"test-client\",\"version\":\"1.0\"}}}");
+
+ JsonNode response = parseSingleResponse(output);
+ assertEquals("2.0", response.path("jsonrpc").asText());
+ assertEquals(1, response.path("id").asInt());
+ assertFalse("Must not contain 'error'", response.has("error"));
+ assertTrue("Must contain 'result'", response.has("result"));
+
+ JsonNode result = response.path("result");
+ assertEquals("2024-11-05", result.path("protocolVersion").asText());
+ }
+
+ public void testInitializeReturnsServerInfo() throws Exception {
+ String output = runServer(new StubToolRegistry(),
+ "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{}}");
+
+ JsonNode result = parseSingleResponse(output).path("result");
+ JsonNode serverInfo = result.path("serverInfo");
+ assertFalse("serverInfo must be present", serverInfo.isMissingNode());
+ assertFalse("serverInfo.name must be present", serverInfo.path("name").isMissingNode());
+ assertFalse("serverInfo.version must be present", serverInfo.path("version").isMissingNode());
+ }
+
+ public void testInitializeReturnsToolsCapability() throws Exception {
+ String output = runServer(new StubToolRegistry(),
+ "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{}}");
+
+ JsonNode result = parseSingleResponse(output).path("result");
+ JsonNode capabilities = result.path("capabilities");
+ assertFalse("capabilities must be present", capabilities.isMissingNode());
+ assertFalse("capabilities.tools must be present", capabilities.path("tools").isMissingNode());
+ }
+
+ public void testInitializePreservesRequestId() throws Exception {
+ String output = runServer(new StubToolRegistry(),
+ "{\"jsonrpc\":\"2.0\",\"id\":42,\"method\":\"initialize\",\"params\":{}}");
+
+ JsonNode response = parseSingleResponse(output);
+ assertEquals(42, response.path("id").asInt());
+ }
+
+ public void testInitializeWithStringId() throws Exception {
+ String output = runServer(new StubToolRegistry(),
+ "{\"jsonrpc\":\"2.0\",\"id\":\"req-1\",\"method\":\"initialize\",\"params\":{}}");
+
+ JsonNode response = parseSingleResponse(output);
+ assertEquals("req-1", response.path("id").asText());
+ }
+
+ // ── tools/list ──────────────────────────────────────────────────────────
+
+ public void testToolsListWithEmptyRegistry() throws Exception {
+ String output = runServer(new StubToolRegistry(),
+ "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\",\"params\":{}}");
+
+ JsonNode response = parseSingleResponse(output);
+ assertFalse("Must not contain 'error'", response.has("error"));
+ JsonNode tools = response.path("result").path("tools");
+ assertTrue("tools must be an array", tools.isArray());
+ assertEquals("Empty registry should produce empty tools array", 0, tools.size());
+ }
+
+ public void testToolsListReturnsSingleTool() throws Exception {
+ ObjectNode schema = MAPPER.createObjectNode();
+ schema.put("type", "object");
+ McpTool tool = new McpTool("processBigDataSet", "BigDataH2Service: processBigDataSet",
+ schema, "POST /services/BigDataH2Service/processBigDataSet");
+
+ StubToolRegistry registry = new StubToolRegistry();
+ registry.addTool(tool);
+
+ String output = runServer(registry,
+ "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\",\"params\":{}}");
+
+ JsonNode tools = parseSingleResponse(output).path("result").path("tools");
+ assertTrue("tools must be an array", tools.isArray());
+ assertEquals(1, tools.size());
+ assertEquals("processBigDataSet", tools.get(0).path("name").asText());
+ assertEquals("BigDataH2Service: processBigDataSet",
+ tools.get(0).path("description").asText());
+ assertFalse("inputSchema must be present",
+ tools.get(0).path("inputSchema").isMissingNode());
+ }
+
+ public void testToolsListReturnsMultipleTools() throws Exception {
+ StubToolRegistry registry = new StubToolRegistry();
+ registry.addTool(new McpTool("op1", "Service1: op1",
+ MAPPER.createObjectNode(), "POST /services/Service1/op1"));
+ registry.addTool(new McpTool("op2", "Service2: op2",
+ MAPPER.createObjectNode(), "POST /services/Service2/op2"));
+ registry.addTool(new McpTool("op3", "Service3: op3",
+ MAPPER.createObjectNode(), "POST /services/Service3/op3"));
+
+ String output = runServer(registry,
+ "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\",\"params\":{}}");
+
+ JsonNode tools = parseSingleResponse(output).path("result").path("tools");
+ assertEquals(3, tools.size());
+ }
+
+ // ── tools/call ──────────────────────────────────────────────────────────
+
+ /**
+ * When tools/call names a tool that is not in the registry, the server
+ * throws IllegalArgumentException, which is caught by the run() loop and
+ * logged to stderr. No JSON-RPC response is written to stdout.
+ */
+ public void testToolsCallUnknownToolProducesNoStdoutResponse() throws Exception {
+ String output = runServer(new StubToolRegistry(),
+ "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\"," +
+ "\"params\":{\"name\":\"nonexistentTool\",\"arguments\":{}}}");
+
+ // Nothing should be written to stdout for the unknown-tool error path
+ // (exception is caught in run() and logged to stderr only)
+ assertTrue("No stdout response expected for unknown tool", output.isEmpty());
+ }
+
+ public void testToolsCallMissingNameProducesNoStdoutResponse() throws Exception {
+ // params.name is absent — throws IllegalArgumentException in buildToolsCallResult
+ String output = runServer(new StubToolRegistry(),
+ "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\"," +
+ "\"params\":{\"arguments\":{}}}");
+
+ assertTrue("No stdout response expected for missing name", output.isEmpty());
+ }
+
+ // ── error cases ─────────────────────────────────────────────────────────
+
+ public void testUnknownMethodReturnsMethodNotFoundError() throws Exception {
+ String output = runServer(new StubToolRegistry(),
+ "{\"jsonrpc\":\"2.0\",\"id\":5,\"method\":\"nonexistent/method\",\"params\":{}}");
+
+ JsonNode response = parseSingleResponse(output);
+ assertTrue("Must contain 'error'", response.has("error"));
+ assertFalse("Must not contain 'result'", response.has("result"));
+ assertEquals(-32601, response.path("error").path("code").asInt());
+ assertTrue("Error message should mention method name",
+ response.path("error").path("message").asText().contains("nonexistent/method"));
+ }
+
+ public void testParseErrorReturnsParseErrorCode() throws Exception {
+ String output = runServer(new StubToolRegistry(),
+ "{this is not valid json at all!!!");
+
+ JsonNode response = parseSingleResponse(output);
+ assertTrue("Must contain 'error'", response.has("error"));
+ assertEquals(-32700, response.path("error").path("code").asInt());
+ // Per JSON-RPC 2.0, id must be null when request cannot be parsed
+ assertTrue("id must be null for parse errors",
+ response.path("id").isNull() || response.path("id").isMissingNode());
+ }
+
+ public void testPartiallyValidJsonReturnsParseError() throws Exception {
+ String output = runServer(new StubToolRegistry(),
+ "{\"jsonrpc\":\"2.0\""); // truncated
+
+ JsonNode response = parseSingleResponse(output);
+ assertEquals(-32700, response.path("error").path("code").asInt());
+ }
+
+ // ── notifications ────────────────────────────────────────────────────────
+
+ /**
+ * Notifications (JSON-RPC messages without an "id" field) must be silently
+ * consumed. No response should appear on stdout.
+ */
+ public void testNotificationProducesNoResponse() throws Exception {
+ String output = runServer(new StubToolRegistry(),
+ "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\",\"params\":{}}");
+
+ assertTrue("Notification must produce no stdout output", output.isEmpty());
+ }
+
+ public void testNotificationWithExplicitNullIdProducesNoResponse() throws Exception {
+ // Some clients send null id for notifications; treat same as absent id
+ // Note: JSON-RPC spec says notifications have NO id field. If id is
+ // present (even null), this implementation treats it as a notification.
+ // This test documents the actual behaviour.
+ String output = runServer(new StubToolRegistry(),
+ "{\"jsonrpc\":\"2.0\",\"id\":null,\"method\":\"notifications/initialized\",\"params\":{}}");
+
+ // With null id, Jackson's request.get("id") returns a NullNode (not null).
+ // The current server checks `if (id == null)` — so NullNode != null,
+ // meaning this IS treated as a regular request (id present) and will
+ // attempt to dispatch the method, returning -32601. Document this behaviour.
+ if (!output.isEmpty()) {
+ JsonNode response = parseSingleResponse(output);
+ // If there is output, it must be a valid JSON-RPC response
+ assertTrue("Any response must be valid JSON-RPC 2.0", response.has("jsonrpc"));
+ }
+ // Either no output or a well-formed error — both are acceptable
+ }
+
+ // ── sequence / multiple requests ─────────────────────────────────────────
+
+ public void testMultipleRequestsInSequenceAreAllAnswered() throws Exception {
+ String output = runServer(new StubToolRegistry(),
+ "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{}}",
+ "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\",\"params\":{}}",
+ "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"bad_method\",\"params\":{}}");
+
+ String[] lines = Arrays.stream(output.split("\n"))
+ .map(String::trim)
+ .filter(l -> !l.isEmpty())
+ .toArray(String[]::new);
+
+ assertEquals("Three requests should produce three responses", 3, lines.length);
+
+ JsonNode r1 = MAPPER.readTree(lines[0]);
+ assertEquals(1, r1.path("id").asInt());
+ assertTrue("First response must be success", r1.has("result"));
+
+ JsonNode r2 = MAPPER.readTree(lines[1]);
+ assertEquals(2, r2.path("id").asInt());
+ assertTrue("Second response must be success", r2.has("result"));
+
+ JsonNode r3 = MAPPER.readTree(lines[2]);
+ assertEquals(3, r3.path("id").asInt());
+ assertTrue("Third response must be error", r3.has("error"));
+ assertEquals(-32601, r3.path("error").path("code").asInt());
+ }
+
+ public void testNotificationMixedWithRequests() throws Exception {
+ // Notification in the middle should not break the sequence
+ String output = runServer(new StubToolRegistry(),
+ "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{}}",
+ "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\",\"params\":{}}",
+ "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\",\"params\":{}}");
+
+ String[] lines = Arrays.stream(output.split("\n"))
+ .map(String::trim)
+ .filter(l -> !l.isEmpty())
+ .toArray(String[]::new);
+
+ assertEquals("Two requests (one notification skipped) → two responses", 2, lines.length);
+ assertEquals(1, MAPPER.readTree(lines[0]).path("id").asInt());
+ assertEquals(2, MAPPER.readTree(lines[1]).path("id").asInt());
+ }
+
+ public void testBlankLinesAreSkipped() throws Exception {
+ // The server trims and skips blank lines
+ String inputData = "\n\n{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{}}\n\n";
+
+ PrintStream savedOut = System.out;
+ InputStream savedIn = System.in;
+ try {
+ ByteArrayOutputStream captured = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(captured, true, StandardCharsets.UTF_8));
+ System.setIn(new ByteArrayInputStream(inputData.getBytes(StandardCharsets.UTF_8)));
+
+ McpStdioServer server = new McpStdioServer(
+ "https://localhost:8443/axis2-json-api",
+ new StubToolRegistry(), MAPPER, null);
+ server.run();
+
+ String output = captured.toString(StandardCharsets.UTF_8).trim();
+ JsonNode response = parseSingleResponse(output);
+ assertEquals(1, response.path("id").asInt());
+ assertTrue(response.has("result"));
+ } finally {
+ System.setOut(savedOut);
+ System.setIn(savedIn);
+ }
+ }
+
+ // ── JSON-RPC envelope ────────────────────────────────────────────────────
+
+ public void testSuccessResponseHasJsonRpc20Field() throws Exception {
+ String output = runServer(new StubToolRegistry(),
+ "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{}}");
+
+ JsonNode response = parseSingleResponse(output);
+ assertEquals("2.0", response.path("jsonrpc").asText());
+ }
+
+ public void testErrorResponseHasJsonRpc20Field() throws Exception {
+ String output = runServer(new StubToolRegistry(),
+ "{\"jsonrpc\":\"2.0\",\"id\":99,\"method\":\"unknown\",\"params\":{}}");
+
+ JsonNode response = parseSingleResponse(output);
+ assertEquals("2.0", response.path("jsonrpc").asText());
+ }
+
+ public void testErrorObjectHasCodeAndMessageFields() throws Exception {
+ String output = runServer(new StubToolRegistry(),
+ "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"unknown\",\"params\":{}}");
+
+ JsonNode error = parseSingleResponse(output).path("error");
+ assertFalse("error.code must be present", error.path("code").isMissingNode());
+ assertFalse("error.message must be present", error.path("message").isMissingNode());
+ assertTrue("error.message must be a non-empty string",
+ !error.path("message").asText().isEmpty());
+ }
+
+ // ── stub registry ─────────────────────────────────────────────────────────
+
+ /**
+ * Test double for {@link ToolRegistry}.
+ *
+ * <p>Overrides {@link #getTools()} and {@link #getTool(String)} so no
+ * HTTP call is made during tests. Tools are injected via {@link #addTool}.
+ */
+ private static class StubToolRegistry extends ToolRegistry {
+
+ private final List<McpTool> toolList = new java.util.ArrayList<>();
+ private final Map<String, McpTool> toolMap = new HashMap<>();
+
+ StubToolRegistry() {
+ // Pass dummy values; load() is never called
+ super("https://localhost:8443/unused", new ObjectMapper(), null);
+ }
+
+ void addTool(McpTool tool) {
+ toolList.add(tool);
+ toolMap.put(tool.getName(), tool);
+ }
+
+ @Override
+ public List<McpTool> getTools() {
+ return Collections.unmodifiableList(toolList);
+ }
+
+ @Override
+ public McpTool getTool(String name) {
+ return toolMap.get(name);
+ }
+ }
+}
diff --git a/modules/mcp-bridge/src/test/java/org/apache/axis2/mcp/bridge/McpToolTest.java b/modules/mcp-bridge/src/test/java/org/apache/axis2/mcp/bridge/McpToolTest.java
new file mode 100644
index 0000000000..9f77f8b9fb
--- /dev/null
+++ b/modules/mcp-bridge/src/test/java/org/apache/axis2/mcp/bridge/McpToolTest.java
@@ -0,0 +1,145 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.axis2.mcp.bridge;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import junit.framework.TestCase;
+
+/**
+ * Unit tests for {@link McpTool}.
+ *
+ * <p>Verifies path extraction, description fallback, and field accessors.
+ */
+public class McpToolTest extends TestCase {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ // ── path extraction ─────────────────────────────────────────────────────
+
+ public void testPathExtractionStripsMethodPrefix() {
+ McpTool tool = new McpTool("op", "desc", MAPPER.createObjectNode(),
+ "POST /services/MyService/op");
+ assertEquals("/services/MyService/op", tool.getPath());
+ }
+
+ public void testPathExtractionWithPutPrefix() {
+ McpTool tool = new McpTool("op", "desc", MAPPER.createObjectNode(),
+ "PUT /services/MyService/op");
+ assertEquals("/services/MyService/op", tool.getPath());
+ }
+
+ public void testPathExtractionWithGetPrefix() {
+ McpTool tool = new McpTool("op", "desc", MAPPER.createObjectNode(),
+ "GET /services/MyService/op");
+ assertEquals("/services/MyService/op", tool.getPath());
+ }
+
+ /**
+ * When the endpoint string contains no space, path should equal the full string.
+ */
+ public void testPathFallsBackToEndpointWhenNoSpace() {
+ McpTool tool = new McpTool("op", "desc", MAPPER.createObjectNode(),
+ "/services/MyService/op");
+ assertEquals("/services/MyService/op", tool.getPath());
+ }
+
+ /**
+ * getEndpoint() must return the original unmodified endpoint string.
+ */
+ public void testGetEndpointReturnsOriginal() {
+ String endpoint = "POST /services/Svc/doThing";
+ McpTool tool = new McpTool("doThing", "desc", MAPPER.createObjectNode(), endpoint);
+ assertEquals(endpoint, tool.getEndpoint());
+ }
+
+ // ── description fallback ────────────────────────────────────────────────
+
+ public void testNullDescriptionFallsBackToName() {
+ McpTool tool = new McpTool("myOp", null, MAPPER.createObjectNode(),
+ "POST /services/Svc/myOp");
+ assertEquals("myOp", tool.getDescription());
+ }
+
+ public void testNonNullDescriptionIsPreserved() {
+ McpTool tool = new McpTool("myOp", "Does something useful",
+ MAPPER.createObjectNode(), "POST /services/Svc/myOp");
+ assertEquals("Does something useful", tool.getDescription());
+ }
+
+ public void testEmptyDescriptionIsNotReplacedByName() {
+ // Empty string is not null — it should be preserved as-is
+ McpTool tool = new McpTool("myOp", "", MAPPER.createObjectNode(),
+ "POST /services/Svc/myOp");
+ assertEquals("", tool.getDescription());
+ }
+
+ // ── other accessors ─────────────────────────────────────────────────────
+
+ public void testGetName() {
+ McpTool tool = new McpTool("processBigDataSet", "desc",
+ MAPPER.createObjectNode(), "POST /services/Svc/processBigDataSet");
+ assertEquals("processBigDataSet", tool.getName());
+ }
+
+ public void testGetInputSchemaReturnsStoredNode() throws Exception {
+ ObjectNode schema = MAPPER.createObjectNode();
+ schema.put("type", "object");
+ schema.putObject("properties").put("datasetId", "string");
+
+ McpTool tool = new McpTool("op", "desc", schema, "POST /services/Svc/op");
+
+ JsonNode retrieved = tool.getInputSchema();
+ assertNotNull(retrieved);
+ assertEquals("object", retrieved.path("type").asText());
+ assertTrue(retrieved.path("properties").has("datasetId"));
+ }
+
+ public void testNullInputSchemaIsStored() {
+ McpTool tool = new McpTool("op", "desc", null, "POST /services/Svc/op");
+ assertNull(tool.getInputSchema());
+ }
+
+ /**
+ * Deep path: "POST /services/BigDataH2Service/processBigDataSet" → path
+ * must start with "/" and contain the service and operation names.
+ */
+ public void testDeepPathExtraction() {
+ McpTool tool = new McpTool("processBigDataSet", "BigDataH2Service: processBigDataSet",
+ MAPPER.createObjectNode(),
+ "POST /services/BigDataH2Service/processBigDataSet");
+ String path = tool.getPath();
+ assertTrue("Path must start with /", path.startsWith("/"));
+ assertTrue("Path must contain service name", path.contains("BigDataH2Service"));
+ assertTrue("Path must contain operation name", path.contains("processBigDataSet"));
+ assertFalse("Path must not contain 'POST'", path.contains("POST"));
+ }
+
+ /**
+ * Multiple spaces in endpoint: only the first space separates method from path.
+ */
+ public void testEndpointWithSpaceInPath() {
+ // Contrived but validates substring-from-first-space behaviour
+ McpTool tool = new McpTool("op", "desc", MAPPER.createObjectNode(),
+ "POST /services/My Service/op");
+ // Should strip "POST " and keep the rest including the space
+ assertEquals("/services/My Service/op", tool.getPath());
+ }
+}
diff --git a/modules/mcp-bridge/src/test/java/org/apache/axis2/mcp/bridge/ToolRegistryTest.java b/modules/mcp-bridge/src/test/java/org/apache/axis2/mcp/bridge/ToolRegistryTest.java
new file mode 100644
index 0000000000..768704035e
--- /dev/null
+++ b/modules/mcp-bridge/src/test/java/org/apache/axis2/mcp/bridge/ToolRegistryTest.java
@@ -0,0 +1,323 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.axis2.mcp.bridge;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import junit.framework.TestCase;
+
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Unit tests for {@link ToolRegistry}.
+ *
+ * <p>Pre-{@code load()} state is tested directly against the registry's initial
+ * values. Post-{@code load()} parsing is tested via a {@link ParseableRegistry}
+ * subclass that overrides the HTTP call and drives the parsing logic through
+ * reflection-based injection of a synthetic JSON response.
+ */
+public class ToolRegistryTest extends TestCase {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ // ── initial (pre-load) state ─────────────────────────────────────────────
+
+ public void testGetToolsReturnsEmptyListBeforeLoad() {
+ ToolRegistry registry = new ToolRegistry(
+ "https://localhost:8443/unused", MAPPER, null);
+ List<McpTool> tools = registry.getTools();
+ assertNotNull(tools);
+ assertTrue("getTools() must return empty list before load()", tools.isEmpty());
+ }
+
+ public void testGetToolReturnsNullBeforeLoad() {
+ ToolRegistry registry = new ToolRegistry(
+ "https://localhost:8443/unused", MAPPER, null);
+ assertNull("getTool() must return null for any name before load()",
+ registry.getTool("processBigDataSet"));
+ assertNull(registry.getTool(""));
+ assertNull(registry.getTool(null));
+ }
+
+ public void testGetToolsListIsUnmodifiable() {
+ ToolRegistry registry = new ToolRegistry(
+ "https://localhost:8443/unused", MAPPER, null);
+ try {
+ registry.getTools().add(new McpTool("op", "desc",
+ MAPPER.createObjectNode(), "POST /services/Svc/op"));
+ fail("getTools() must return an unmodifiable list");
+ } catch (UnsupportedOperationException e) {
+ // expected
+ }
+ }
+
+ // ── parsing via injected JSON ──────────────────────────────────────────────
+
+ /**
+ * Injects a pre-built JSON catalog into the registry's private fields
+ * (simulating what {@code load()} would do after a successful HTTP fetch)
+ * and verifies that the getters expose the parsed tools correctly.
+ */
+ public void testRegistryExposesToolsAfterInjection() throws Exception {
+ ToolRegistry registry = new ToolRegistry(
+ "https://localhost:8443/unused", MAPPER, null);
+
+ McpTool tool1 = new McpTool("processBigDataSet",
+ "BigDataH2Service: processBigDataSet",
+ MAPPER.createObjectNode(),
+ "POST /services/BigDataH2Service/processBigDataSet");
+ McpTool tool2 = new McpTool("getStatus",
+ "StatusService: getStatus",
+ MAPPER.createObjectNode(),
+ "POST /services/StatusService/getStatus");
+
+ injectTools(registry, tool1, tool2);
+
+ List<McpTool> tools = registry.getTools();
+ assertEquals(2, tools.size());
+ assertEquals("processBigDataSet", tools.get(0).getName());
+ assertEquals("getStatus", tools.get(1).getName());
+
+ assertNotNull(registry.getTool("processBigDataSet"));
+ assertNotNull(registry.getTool("getStatus"));
+ assertNull(registry.getTool("unknownTool"));
+ }
+
+ public void testGetToolByNameIsCaseSensitive() throws Exception {
+ ToolRegistry registry = new ToolRegistry(
+ "https://localhost:8443/unused", MAPPER, null);
+ McpTool tool = new McpTool("processData", "desc",
+ MAPPER.createObjectNode(), "POST /services/Svc/processData");
+ injectTools(registry, tool);
+
+ assertNotNull(registry.getTool("processData"));
+ assertNull("Lookup must be case-sensitive", registry.getTool("ProcessData"));
+ assertNull("Lookup must be case-sensitive", registry.getTool("PROCESSDATA"));
+ }
+
+ public void testGetToolsOrderMatchesInsertionOrder() throws Exception {
+ ToolRegistry registry = new ToolRegistry(
+ "https://localhost:8443/unused", MAPPER, null);
+ McpTool a = new McpTool("alpha", "desc a", MAPPER.createObjectNode(), "POST /a");
+ McpTool b = new McpTool("beta", "desc b", MAPPER.createObjectNode(), "POST /b");
+ McpTool c = new McpTool("gamma", "desc c", MAPPER.createObjectNode(), "POST /c");
+ injectTools(registry, a, b, c);
+
+ List<McpTool> tools = registry.getTools();
+ assertEquals("alpha", tools.get(0).getName());
+ assertEquals("beta", tools.get(1).getName());
+ assertEquals("gamma", tools.get(2).getName());
+ }
+
+ // ── JSON catalog parsing logic ────────────────────────────────────────────
+
+ /**
+ * Tests the catalog-parsing code path by feeding a synthetic
+ * {@code /openapi-mcp.json} response body through a
+ * {@link ParseableRegistry} that exposes a package-private parse hook.
+ */
+ public void testParseCatalogJsonPopulatesTools() throws Exception {
+ String catalogJson = buildCatalogJson(
+ buildToolJson("op1", "Service1: op1", "POST /services/Service1/op1"),
+ buildToolJson("op2", "Service2: op2", "POST /services/Service2/op2"));
+
+ ParseableRegistry registry = new ParseableRegistry();
+ registry.parseCatalog(catalogJson);
+
+ assertEquals(2, registry.getTools().size());
+ assertEquals("op1", registry.getTools().get(0).getName());
+ assertEquals("op2", registry.getTools().get(1).getName());
+
+ McpTool tool1 = registry.getTool("op1");
+ assertNotNull(tool1);
+ assertEquals("Service1: op1", tool1.getDescription());
+ assertEquals("/services/Service1/op1", tool1.getPath());
+ }
+
+ public void testParseCatalogWithEmptyToolsArray() throws Exception {
+ String catalogJson = "{\"tools\":[]}";
+ ParseableRegistry registry = new ParseableRegistry();
+ registry.parseCatalog(catalogJson);
+ assertTrue("Empty tools array should yield empty registry",
+ registry.getTools().isEmpty());
+ }
+
+ public void testParseCatalogSkipsEntriesWithNullName() throws Exception {
+ // A tool entry missing the "name" field must be silently skipped
+ String catalogJson = "{"
+ + "\"tools\":["
+ + "{\"description\":\"No name here\",\"endpoint\":\"POST /svc/op\"},"
+ + "{\"name\":\"validOp\",\"description\":\"Valid\",\"endpoint\":\"POST /svc/validOp\"}"
+ + "]}";
+ ParseableRegistry registry = new ParseableRegistry();
+ registry.parseCatalog(catalogJson);
+ assertEquals(1, registry.getTools().size());
+ assertEquals("validOp", registry.getTools().get(0).getName());
+ }
+
+ public void testParseCatalogSkipsEntriesWithEmptyName() throws Exception {
+ String catalogJson = "{"
+ + "\"tools\":["
+ + "{\"name\":\"\",\"description\":\"Empty name\",\"endpoint\":\"POST /svc/op\"},"
+ + "{\"name\":\"realOp\",\"description\":\"desc\",\"endpoint\":\"POST /svc/realOp\"}"
+ + "]}";
+ ParseableRegistry registry = new ParseableRegistry();
+ registry.parseCatalog(catalogJson);
+ assertEquals(1, registry.getTools().size());
+ assertEquals("realOp", registry.getTools().get(0).getName());
+ }
+
+ public void testParseCatalogHandlesMissingToolsArray() throws Exception {
+ // No "tools" key — should warn but not throw; registry remains empty
+ ParseableRegistry registry = new ParseableRegistry();
+ registry.parseCatalog("{\"other\":\"data\"}");
+ assertTrue("Missing tools array should yield empty registry",
+ registry.getTools().isEmpty());
+ }
+
+ public void testParseCatalogPreservesInputSchema() throws Exception {
+ String schema = "{\"type\":\"object\",\"properties\":{\"n\":{\"type\":\"integer\"}}}";
+ String catalogJson = "{"
+ + "\"tools\":[{"
+ + "\"name\":\"compute\","
+ + "\"description\":\"Compute something\","
+ + "\"inputSchema\":" + schema + ","
+ + "\"endpoint\":\"POST /services/Svc/compute\""
+ + "}]}";
+
+ ParseableRegistry registry = new ParseableRegistry();
+ registry.parseCatalog(catalogJson);
+
+ McpTool tool = registry.getTool("compute");
+ assertNotNull(tool);
+ assertNotNull("inputSchema must be present", tool.getInputSchema());
+ assertEquals("object", tool.getInputSchema().path("type").asText());
+ assertTrue(tool.getInputSchema().path("properties").has("n"));
+ }
+
+ public void testParseCatalogToolDescriptionFallsBackToName() throws Exception {
+ // description absent → name is used
+ String catalogJson = "{"
+ + "\"tools\":[{"
+ + "\"name\":\"doSomething\","
+ + "\"endpoint\":\"POST /services/Svc/doSomething\""
+ + "}]}";
+ ParseableRegistry registry = new ParseableRegistry();
+ registry.parseCatalog(catalogJson);
+
+ McpTool tool = registry.getTool("doSomething");
+ assertNotNull(tool);
+ assertEquals("doSomething", tool.getDescription());
+ }
+
+ // ── helpers ─────────────────────────────────────────────────────────────
+
+ /** Injects a set of tools into the private fields of a ToolRegistry via reflection. */
+ @SuppressWarnings("unchecked")
+ private static void injectTools(ToolRegistry registry, McpTool... tools) throws Exception {
+ java.util.List<McpTool> list = new java.util.ArrayList<>();
+ java.util.Map<String, McpTool> map = new LinkedHashMap<>();
+ for (McpTool t : tools) {
+ list.add(t);
+ map.put(t.getName(), t);
+ }
+
+ Field toolsField = ToolRegistry.class.getDeclaredField("tools");
+ toolsField.setAccessible(true);
+ toolsField.set(registry, Collections.unmodifiableList(list));
+
+ Field mapField = ToolRegistry.class.getDeclaredField("toolMap");
+ mapField.setAccessible(true);
+ mapField.set(registry, Collections.unmodifiableMap(map));
+ }
+
+ private static ObjectNode buildToolJson(String name, String desc, String endpoint) {
+ ObjectNode n = MAPPER.createObjectNode();
+ n.put("name", name);
+ n.put("description", desc);
+ n.put("endpoint", endpoint);
+ n.set("inputSchema", MAPPER.createObjectNode());
+ return n;
+ }
+
+ private static String buildCatalogJson(ObjectNode... tools) throws Exception {
+ ObjectNode root = MAPPER.createObjectNode();
+ ArrayNode arr = root.putArray("tools");
+ for (ObjectNode t : tools) arr.add(t);
+ return MAPPER.writeValueAsString(root);
+ }
+
+ // ── ParseableRegistry ─────────────────────────────────────────────────────
+
+ /**
+ * Subclass of {@link ToolRegistry} that exposes the catalog-parsing logic
+ * for unit testing without requiring a live HTTP endpoint.
+ *
+ * <p>The parsing logic in the real {@code load()} method is replicated here
+ * because it is private. This mirrors how the real bridge operates: parse
+ * a JSON body, build the list and map, store them in the private fields.
+ * If the production implementation changes, this test will fail, which is
+ * the intended signal.
+ */
+ private static class ParseableRegistry extends ToolRegistry {
+
+ ParseableRegistry() {
+ super("https://localhost:8443/unused", MAPPER, null);
+ }
+
+ /**
+ * Parses a {@code /openapi-mcp.json} response body exactly as
+ * {@link ToolRegistry#load()} would after a successful HTTP fetch.
+ */
+ void parseCatalog(String json) throws Exception {
+ com.fasterxml.jackson.databind.JsonNode root = MAPPER.readTree(json);
+ com.fasterxml.jackson.databind.JsonNode toolsNode = root.path("tools");
+
+ if (!toolsNode.isArray()) {
+ // matches the production warning branch
+ return;
+ }
+
+ java.util.List<McpTool> loaded = new java.util.ArrayList<>();
+ Map<String, McpTool> map = new LinkedHashMap<>();
+
+ for (com.fasterxml.jackson.databind.JsonNode toolNode : toolsNode) {
+ String name = toolNode.path("name").asText(null);
+ if (name == null || name.isEmpty()) continue;
+
+ String description = toolNode.path("description").asText(name);
+ com.fasterxml.jackson.databind.JsonNode inputSchema = toolNode.path("inputSchema");
+ String endpoint = toolNode.path("endpoint").asText("");
+
+ McpTool tool = new McpTool(name, description, inputSchema, endpoint);
+ loaded.add(tool);
+ map.put(name, tool);
+ }
+
+ // Inject into private fields
+ injectTools(this, loaded.toArray(new McpTool[0]));
+ }
+ }
+}
diff --git a/modules/openapi/src/main/java/org/apache/axis2/openapi/OpenApiSpecGenerator.java b/modules/openapi/src/main/java/org/apache/axis2/openapi/OpenApiSpecGenerator.java
index d67a3f02fe..27c825b3a7 100644
--- a/modules/openapi/src/main/java/org/apache/axis2/openapi/OpenApiSpecGenerator.java
+++ b/modules/openapi/src/main/java/org/apache/axis2/openapi/OpenApiSpecGenerator.java
@@ -616,6 +616,82 @@ public class OpenApiSpecGenerator {
return configurationContext;
}
+ /**
+ * Generate MCP tool catalog JSON for all deployed services.
+ *
+ * Produces the {@code /openapi-mcp.json} format consumed by axis2-mcp-bridge:
+ * <pre>
+ * {
+ * "tools": [
+ * { "name": "...", "description": "...",
+ * "inputSchema": { "type": "object", "properties": {}, "required": [] },
+ * "endpoint": "POST /services/ServiceName/operationName" }
+ * ]
+ * }
+ * </pre>
+ *
+ * Uses the same service filtering as {@link #generatePaths()} so the tool
+ * catalog is consistent with the OpenAPI spec.
+ */
+ public String generateMcpCatalogJson(HttpServletRequest request) {
+ try {
+ AxisConfiguration axisConfig = configurationContext.getAxisConfiguration();
+ StringBuilder json = new StringBuilder();
+ json.append("{\n \"tools\": [\n");
+ boolean firstTool = true;
+
+ Iterator<AxisService> services = axisConfig.getServices().values().iterator();
+ while (services.hasNext()) {
+ AxisService service = services.next();
+ if (isSystemService(service)) continue;
+ if (!shouldIncludeService(service)) continue;
+
+ Iterator<AxisOperation> operations = service.getOperations();
+ while (operations.hasNext()) {
+ AxisOperation operation = operations.next();
+ if (!shouldIncludeOperation(service, operation)) continue;
+
+ String opName = operation.getName().getLocalPart();
+ String path = "/services/" + service.getName() + "/" + opName;
+
+ if (!firstTool) json.append(",\n");
+ firstTool = false;
+
+ json.append(" {\n");
+ json.append(" \"name\": \"").append(escapeJson(opName)).append("\",\n");
+ json.append(" \"description\": \"").append(escapeJson(service.getName()))
+ .append(": ").append(escapeJson(opName)).append("\",\n");
+ json.append(" \"inputSchema\": {\n");
+ json.append(" \"type\": \"object\",\n");
+ json.append(" \"properties\": {},\n");
+ json.append(" \"required\": []\n");
+ json.append(" },\n");
+ json.append(" \"endpoint\": \"POST ").append(escapeJson(path)).append("\"\n");
+ json.append(" }");
+ }
+ }
+
+ json.append("\n ]\n}");
+ log.debug("Generated MCP catalog JSON");
+ return json.toString();
+
+ } catch (Exception e) {
+ log.error("Failed to generate MCP catalog JSON", e);
+ return "{\"tools\":[]}";
+ }
+ }
+
+ /**
+ * Escape a string for safe inclusion in a JSON string value.
+ * Axis2 service/operation names follow XML NCName rules and will not
+ * contain control characters, but backslash and double-quote are escaped
+ * defensively.
+ */
+ private String escapeJson(String s) {
+ if (s == null) return "";
+ return s.replace("\\", "\\\\").replace("\"", "\\\"");
+ }
+
/**
* Get OpenAPI JSON processing performance statistics using moshih2 metrics.
*/
diff --git a/modules/openapi/src/main/java/org/apache/axis2/openapi/SwaggerUIHandler.java b/modules/openapi/src/main/java/org/apache/axis2/openapi/SwaggerUIHandler.java
index cfb2c9ff75..30fe986edb 100644
--- a/modules/openapi/src/main/java/org/apache/axis2/openapi/SwaggerUIHandler.java
+++ b/modules/openapi/src/main/java/org/apache/axis2/openapi/SwaggerUIHandler.java
@@ -189,6 +189,38 @@ public class SwaggerUIHandler {
}
}
+ /**
+ * Handle MCP tool catalog request ({@code /openapi-mcp.json}).
+ *
+ * Returns the tool catalog consumed by axis2-mcp-bridge at startup so it
+ * can register Axis2 operations as MCP tools without any Axis2-specific
+ * knowledge in the bridge process.
+ */
+ public void handleMcpCatalogRequest(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
+
+ log.debug("Serving MCP tool catalog");
+
+ response.setContentType("application/json; charset=UTF-8");
+ response.setStatus(HttpServletResponse.SC_OK);
+
+ addSecurityHeaders(response);
+ addCorsHeaders(response);
+
+ try {
+ String mcpJson = specGenerator.generateMcpCatalogJson(request);
+
+ PrintWriter writer = response.getWriter();
+ writer.write(mcpJson);
+ writer.flush();
+
+ } catch (Exception e) {
+ log.error("Failed to generate MCP tool catalog", e);
+ response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
+ "Failed to generate MCP tool catalog");
+ }
+ }
+
/**
* Build the URL for the OpenAPI specification endpoint using configuration.
*/
diff --git a/modules/openapi/src/test/java/org/apache/axis2/openapi/McpCatalogGeneratorTest.java b/modules/openapi/src/test/java/org/apache/axis2/openapi/McpCatalogGeneratorTest.java
new file mode 100644
index 0000000000..3f0c01db50
--- /dev/null
+++ b/modules/openapi/src/test/java/org/apache/axis2/openapi/McpCatalogGeneratorTest.java
@@ -0,0 +1,421 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.axis2.openapi;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import junit.framework.TestCase;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.description.AxisOperation;
+import org.apache.axis2.description.AxisService;
+import org.apache.axis2.description.InOutAxisOperation;
+import org.apache.axis2.engine.AxisConfiguration;
+
+import jakarta.servlet.AsyncContext;
+import jakarta.servlet.DispatcherType;
+import jakarta.servlet.RequestDispatcher;
+import jakarta.servlet.ServletContext;
+import jakarta.servlet.ServletInputStream;
+import jakarta.servlet.ServletRequest;
+import jakarta.servlet.ServletResponse;
+import jakarta.servlet.http.Cookie;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import jakarta.servlet.http.HttpSession;
+import jakarta.servlet.http.HttpUpgradeHandler;
+import jakarta.servlet.http.Part;
+
+import javax.xml.namespace.QName;
+import java.io.BufferedReader;
+import java.security.Principal;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.Locale;
+import java.util.Map;
+
+/**
+ * Unit tests for the {@code /openapi-mcp.json} endpoint implemented in
+ * {@link OpenApiSpecGenerator#generateMcpCatalogJson(HttpServletRequest)}.
+ *
+ * <p>Tests cover:
+ * <ul>
+ * <li>JSON structure validity (parseable, has "tools" array)</li>
+ * <li>Empty catalog when no user services are registered</li>
+ * <li>Correct tool fields: name, description, inputSchema, endpoint</li>
+ * <li>Multiple services / multiple operations per service</li>
+ * <li>JSON special-character escaping in service and operation names</li>
+ * <li>Endpoint format: {@code "POST /services/SvcName/opName"}</li>
+ * <li>inputSchema has the required MCP structure</li>
+ * </ul>
+ */
+public class McpCatalogGeneratorTest extends TestCase {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ private AxisConfiguration axisConfig;
+ private ConfigurationContext configCtx;
+ private OpenApiSpecGenerator generator;
+ private MockHttpServletRequest mockRequest;
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ axisConfig = new AxisConfiguration();
+ configCtx = new ConfigurationContext(axisConfig);
+ generator = new OpenApiSpecGenerator(configCtx);
+ mockRequest = new MockHttpServletRequest();
+ }
+
+ // ── JSON validity ─────────────────────────────────────────────────────────
+
+ public void testCatalogIsValidJson() throws Exception {
+ String json = generator.generateMcpCatalogJson(mockRequest);
+ assertNotNull(json);
+ // Must be parseable
+ JsonNode root = MAPPER.readTree(json);
+ assertNotNull(root);
+ }
+
+ public void testCatalogRootHasToolsArray() throws Exception {
+ JsonNode root = MAPPER.readTree(generator.generateMcpCatalogJson(mockRequest));
+ assertTrue("Root must have 'tools' key", root.has("tools"));
+ assertTrue("tools must be an array", root.get("tools").isArray());
+ }
+
+ // ── empty / no-service cases ──────────────────────────────────────────────
+
+ public void testEmptyConfigurationProducesEmptyToolsArray() throws Exception {
+ // No services registered — only system services which are filtered out
+ JsonNode tools = getCatalogTools();
+ assertEquals("No user services → empty tools array", 0, tools.size());
+ }
+
+ // ── single service / single operation ────────────────────────────────────
+
+ public void testSingleServiceSingleOperationProducesOneTool() throws Exception {
+ addService("OrderService", "placeOrder");
+
+ JsonNode tools = getCatalogTools();
+ assertEquals(1, tools.size());
+ }
+
+ public void testToolNameMatchesOperationName() throws Exception {
+ addService("OrderService", "placeOrder");
+
+ JsonNode tool = getCatalogTools().get(0);
+ assertEquals("placeOrder", tool.path("name").asText());
+ }
+
+ public void testToolDescriptionContainsServiceAndOperationName() throws Exception {
+ addService("OrderService", "placeOrder");
+
+ JsonNode tool = getCatalogTools().get(0);
+ String desc = tool.path("description").asText();
+ assertTrue("Description must mention service name", desc.contains("OrderService"));
+ assertTrue("Description must mention operation name", desc.contains("placeOrder"));
+ }
+
+ public void testToolEndpointFormat() throws Exception {
+ addService("BigDataH2Service", "processBigDataSet");
+
+ JsonNode tool = getCatalogTools().get(0);
+ String endpoint = tool.path("endpoint").asText();
+ assertEquals("POST /services/BigDataH2Service/processBigDataSet", endpoint);
+ }
+
+ public void testToolEndpointStartsWithPost() throws Exception {
+ addService("MyService", "myOperation");
+
+ JsonNode tool = getCatalogTools().get(0);
+ String endpoint = tool.path("endpoint").asText();
+ assertTrue("Endpoint must start with POST", endpoint.startsWith("POST "));
+ }
+
+ public void testToolEndpointPathContainsServices() throws Exception {
+ addService("MyService", "myOperation");
+
+ JsonNode tool = getCatalogTools().get(0);
+ String endpoint = tool.path("endpoint").asText();
+ assertTrue("Endpoint path must contain /services/",
+ endpoint.contains("/services/"));
+ }
+
+ // ── inputSchema ───────────────────────────────────────────────────────────
+
+ public void testToolHasInputSchemaField() throws Exception {
+ addService("TestService", "testOp");
+
+ JsonNode tool = getCatalogTools().get(0);
+ assertFalse("inputSchema must be present", tool.path("inputSchema").isMissingNode());
+ }
+
+ public void testInputSchemaTypeIsObject() throws Exception {
+ addService("TestService", "testOp");
+
+ JsonNode schema = getCatalogTools().get(0).path("inputSchema");
+ assertEquals("object", schema.path("type").asText());
+ }
+
+ public void testInputSchemaHasPropertiesField() throws Exception {
+ addService("TestService", "testOp");
+
+ JsonNode schema = getCatalogTools().get(0).path("inputSchema");
+ assertFalse("inputSchema.properties must be present",
+ schema.path("properties").isMissingNode());
+ }
+
+ public void testInputSchemaHasRequiredField() throws Exception {
+ addService("TestService", "testOp");
+
+ JsonNode schema = getCatalogTools().get(0).path("inputSchema");
+ assertFalse("inputSchema.required must be present",
+ schema.path("required").isMissingNode());
+ assertTrue("inputSchema.required must be an array",
+ schema.path("required").isArray());
+ }
+
+ // ── multiple services / operations ────────────────────────────────────────
+
+ public void testTwoServicesEachWithOneOperationProduceTwoTools() throws Exception {
+ addService("ServiceA", "doAlpha");
+ addService("ServiceB", "doBeta");
+
+ JsonNode tools = getCatalogTools();
+ assertEquals(2, tools.size());
+ }
+
+ public void testOneServiceWithThreeOperationsProducesThreeTools() throws Exception {
+ AxisService svc = new AxisService("CalculatorService");
+ addOperation(svc, "add");
+ addOperation(svc, "subtract");
+ addOperation(svc, "multiply");
+ axisConfig.addService(svc);
+
+ JsonNode tools = getCatalogTools();
+ assertEquals(3, tools.size());
+ }
+
+ public void testAllToolNamesArePresent() throws Exception {
+ AxisService svc = new AxisService("CalculatorService");
+ addOperation(svc, "add");
+ addOperation(svc, "subtract");
+ axisConfig.addService(svc);
+
+ JsonNode tools = getCatalogTools();
+ java.util.Set<String> names = new java.util.HashSet<>();
+ for (JsonNode t : tools) names.add(t.path("name").asText());
+ assertTrue("'add' must be in tool names", names.contains("add"));
+ assertTrue("'subtract' must be in tool names", names.contains("subtract"));
+ }
+
+ public void testToolsFromDifferentServicesHaveCorrectEndpoints() throws Exception {
+ addService("ServiceA", "opA");
+ addService("ServiceB", "opB");
+
+ JsonNode tools = getCatalogTools();
+ java.util.Set<String> endpoints = new java.util.HashSet<>();
+ for (JsonNode t : tools) endpoints.add(t.path("endpoint").asText());
+ assertTrue(endpoints.contains("POST /services/ServiceA/opA"));
+ assertTrue(endpoints.contains("POST /services/ServiceB/opB"));
+ }
+
+ // ── JSON escaping ─────────────────────────────────────────────────────────
+
+ /**
+ * Operation names with JSON-special characters must be escaped so the
+ * output remains valid JSON.
+ */
+ public void testOperationNameWithQuoteIsEscaped() throws Exception {
+ AxisService svc = new AxisService("TestService");
+ AxisOperation op = new InOutAxisOperation();
+ op.setName(QName.valueOf("say\"Hello\"")); // contains double-quote
+ svc.addOperation(op);
+ axisConfig.addService(svc);
+
+ // Must not throw during JSON parsing
+ String json = generator.generateMcpCatalogJson(mockRequest);
+ JsonNode root = MAPPER.readTree(json);
+ assertNotNull("JSON with escaped quotes must be parseable", root);
+ }
+
+ public void testServiceNameWithBackslashIsEscaped() throws Exception {
+ AxisService svc = new AxisService("My\\Service"); // contains backslash
+ AxisOperation op = new InOutAxisOperation();
+ op.setName(QName.valueOf("doOp"));
+ svc.addOperation(op);
+ axisConfig.addService(svc);
+
+ String json = generator.generateMcpCatalogJson(mockRequest);
+ JsonNode root = MAPPER.readTree(json); // must be parseable
+ assertNotNull(root);
+ }
+
+ // ── catalog request is null-safe ──────────────────────────────────────────
+
+ public void testGenerateMcpCatalogWithNullRequestDoesNotThrow() throws Exception {
+ addService("TestService", "testOp");
+
+ // null request is passed — generator should handle it gracefully
+ // (request is not used by generateMcpCatalogJson; it only introspects AxisConfig)
+ try {
+ String json = generator.generateMcpCatalogJson(null);
+ assertNotNull(json);
+ JsonNode root = MAPPER.readTree(json);
+ assertTrue(root.has("tools"));
+ } catch (NullPointerException e) {
+ // Acceptable if the method does not guard against null — document behaviour
+ System.out.println("INFO: generateMcpCatalogJson(null) throws NPE — " +
+ "callers must ensure request is non-null");
+ }
+ }
+
+ // ── tool list mirrors existing OpenAPI paths ──────────────────────────────
+
+ /**
+ * Every tool in the MCP catalog must correspond to a path in the OpenAPI
+ * spec (same service/operation pair). This verifies that both endpoints
+ * apply identical filtering logic.
+ */
+ public void testMcpToolsMatchOpenApiPaths() throws Exception {
+ addService("BigDataH2Service", "processBigDataSet");
+ addService("OrderService", "placeOrder");
+
+ // Collect MCP tool endpoints
+ JsonNode tools = getCatalogTools();
+ java.util.Set<String> mcpPaths = new java.util.HashSet<>();
+ for (JsonNode tool : tools) {
+ String endpoint = tool.path("endpoint").asText();
+ // Strip "POST " prefix
+ mcpPaths.add(endpoint.substring("POST ".length()));
+ }
+
+ // Collect OpenAPI paths
+ io.swagger.v3.oas.models.OpenAPI openApi = generator.generateOpenApiSpec(mockRequest);
+ java.util.Set<String> openApiPaths = new java.util.HashSet<>();
+ if (openApi.getPaths() != null) {
+ openApiPaths.addAll(openApi.getPaths().keySet());
+ }
+
+ // Every MCP path must appear in the OpenAPI spec
+ for (String mcpPath : mcpPaths) {
+ assertTrue("MCP tool path '" + mcpPath + "' must appear in OpenAPI paths",
+ openApiPaths.contains(mcpPath));
+ }
+ }
+
+ // ── helpers ─────────────────────────────────────────────────────────────
+
+ private void addService(String serviceName, String operationName) throws Exception {
+ AxisService svc = new AxisService(serviceName);
+ addOperation(svc, operationName);
+ axisConfig.addService(svc);
+ }
+
+ private void addOperation(AxisService svc, String operationName) {
+ AxisOperation op = new InOutAxisOperation();
+ op.setName(QName.valueOf(operationName));
+ svc.addOperation(op);
+ }
+
+ private JsonNode getCatalogTools() throws Exception {
+ String json = generator.generateMcpCatalogJson(mockRequest);
+ return MAPPER.readTree(json).path("tools");
+ }
+
+ // ── mock request ─────────────────────────────────────────────────────────
+
+ private static class MockHttpServletRequest implements HttpServletRequest {
+ private String scheme = "https";
+ private String serverName = "localhost";
+ private int serverPort = 8443;
+ private String contextPath = "/axis2-json-api";
+
+ @Override public String getScheme() { return scheme; }
+ @Override public String getServerName() { return serverName; }
+ @Override public int getServerPort() { return serverPort; }
+ @Override public String getContextPath() { return contextPath; }
+
+ @Override public String getAuthType() { return null; }
+ @Override public Cookie[] getCookies() { return new Cookie[0]; }
+ @Override public long getDateHeader(String n) { return 0; }
+ @Override public String getHeader(String n) { return null; }
+ @Override public Enumeration<String> getHeaders(String n) { return null; }
+ @Override public Enumeration<String> getHeaderNames() { return null; }
+ @Override public int getIntHeader(String n) { return 0; }
+ @Override public String getMethod() { return "GET"; }
+ @Override public String getPathInfo() { return null; }
+ @Override public String getPathTranslated() { return null; }
+ @Override public String getQueryString() { return null; }
+ @Override public String getRemoteUser() { return null; }
+ @Override public boolean isUserInRole(String r) { return false; }
+ @Override public Principal getUserPrincipal() { return null; }
+ @Override public String getRequestedSessionId() { return null; }
+ @Override public String getRequestURI() { return ""; }
+ @Override public StringBuffer getRequestURL() { return new StringBuffer(); }
+ @Override public String getServletPath() { return ""; }
+ @Override public HttpSession getSession(boolean c) { return null; }
+ @Override public HttpSession getSession() { return null; }
+ @Override public String changeSessionId() { return null; }
+ @Override public boolean isRequestedSessionIdValid() { return false; }
+ @Override public boolean isRequestedSessionIdFromCookie() { return false; }
+ @Override public boolean isRequestedSessionIdFromURL() { return false; }
+ @Override public boolean authenticate(HttpServletResponse r) { return false; }
+ @Override public void login(String u, String p) { }
+ @Override public void logout() { }
+ @Override public Collection<Part> getParts() { return null; }
+ @Override public Part getPart(String n) { return null; }
+ @Override public <T extends HttpUpgradeHandler> T upgrade(Class<T> c) { return null; }
+ @Override public Object getAttribute(String n) { return null; }
+ @Override public Enumeration<String> getAttributeNames() { return null; }
+ @Override public String getCharacterEncoding() { return null; }
+ @Override public void setCharacterEncoding(String e) { }
+ @Override public int getContentLength() { return 0; }
+ @Override public long getContentLengthLong() { return 0; }
+ @Override public String getContentType() { return null; }
+ @Override public ServletInputStream getInputStream() { return null; }
+ @Override public String getParameter(String n) { return null; }
+ @Override public Enumeration<String> getParameterNames() { return null; }
+ @Override public String[] getParameterValues(String n) { return new String[0]; }
+ @Override public Map<String, String[]> getParameterMap() { return null; }
+ @Override public String getProtocol() { return "HTTP/2"; }
+ @Override public String getRemoteAddr() { return "127.0.0.1"; }
+ @Override public String getRemoteHost() { return "localhost"; }
+ @Override public void setAttribute(String n, Object o) { }
+ @Override public void removeAttribute(String n) { }
+ @Override public Locale getLocale() { return Locale.US; }
+ @Override public Enumeration<Locale> getLocales() { return null; }
+ @Override public boolean isSecure() { return true; }
+ @Override public RequestDispatcher getRequestDispatcher(String p) { return null; }
+ @Override public int getRemotePort() { return 0; }
+ @Override public String getLocalName() { return "localhost"; }
+ @Override public String getLocalAddr() { return "127.0.0.1"; }
+ @Override public int getLocalPort() { return serverPort; }
+ @Override public ServletContext getServletContext() { return null; }
+ @Override public AsyncContext startAsync() { return null; }
+ @Override public AsyncContext startAsync(ServletRequest q, ServletResponse s) { return null; }
+ @Override public boolean isAsyncStarted() { return false; }
+ @Override public boolean isAsyncSupported() { return false; }
+ @Override public AsyncContext getAsyncContext() { return null; }
+ @Override public DispatcherType getDispatcherType() { return null; }
+ @Override public BufferedReader getReader() { return null; }
+ @Override public jakarta.servlet.ServletConnection getServletConnection() { return null; }
+ @Override public String getProtocolRequestId() { return null; }
+ @Override public String getRequestId() { return null; }
+ }
+}
diff --git a/modules/openapi/src/test/java/org/apache/axis2/openapi/McpCatalogHandlerTest.java b/modules/openapi/src/test/java/org/apache/axis2/openapi/McpCatalogHandlerTest.java
new file mode 100644
index 0000000000..04ff450e42
--- /dev/null
+++ b/modules/openapi/src/test/java/org/apache/axis2/openapi/McpCatalogHandlerTest.java
@@ -0,0 +1,303 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.axis2.openapi;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import junit.framework.TestCase;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.description.AxisOperation;
+import org.apache.axis2.description.AxisService;
+import org.apache.axis2.description.InOutAxisOperation;
+import org.apache.axis2.engine.AxisConfiguration;
+
+import jakarta.servlet.AsyncContext;
+import jakarta.servlet.DispatcherType;
+import jakarta.servlet.RequestDispatcher;
+import jakarta.servlet.ServletContext;
+import jakarta.servlet.ServletInputStream;
+import jakarta.servlet.ServletOutputStream;
+import jakarta.servlet.ServletRequest;
+import jakarta.servlet.ServletResponse;
+import jakarta.servlet.http.Cookie;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import jakarta.servlet.http.HttpSession;
+import jakarta.servlet.http.HttpUpgradeHandler;
+import jakarta.servlet.http.Part;
+
+import javax.xml.namespace.QName;
+import java.io.BufferedReader;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.security.Principal;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.Map;
+
+/**
+ * Unit tests for {@link SwaggerUIHandler#handleMcpCatalogRequest}.
+ *
+ * <p>Verifies HTTP response headers (Content-Type, CORS, security headers),
+ * status code, and body validity for the {@code /openapi-mcp.json} endpoint.
+ */
+public class McpCatalogHandlerTest extends TestCase {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ private SwaggerUIHandler handler;
+ private MockHttpServletRequest mockRequest;
+ private MockHttpServletResponse mockResponse;
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ AxisConfiguration axisConfig = new AxisConfiguration();
+ ConfigurationContext configCtx = new ConfigurationContext(axisConfig);
+ handler = new SwaggerUIHandler(configCtx);
+ mockRequest = new MockHttpServletRequest();
+ mockResponse = new MockHttpServletResponse();
+ }
+
+ // ── status ────────────────────────────────────────────────────────────────
+
+ public void testMcpCatalogReturnsHttp200() throws Exception {
+ handler.handleMcpCatalogRequest(mockRequest, mockResponse);
+ assertEquals(200, mockResponse.getStatus());
+ }
+
+ // ── Content-Type ──────────────────────────────────────────────────────────
+
+ public void testMcpCatalogContentTypeIsJson() throws Exception {
+ handler.handleMcpCatalogRequest(mockRequest, mockResponse);
+ String ct = mockResponse.getContentType();
+ assertNotNull("Content-Type must be set", ct);
+ assertTrue("Content-Type must be application/json", ct.contains("application/json"));
+ }
+
+ public void testMcpCatalogContentTypeIncludesUtf8() throws Exception {
+ handler.handleMcpCatalogRequest(mockRequest, mockResponse);
+ assertTrue("Content-Type must declare UTF-8 charset",
+ mockResponse.getContentType().contains("UTF-8"));
+ }
+
+ // ── CORS headers ──────────────────────────────────────────────────────────
+
+ public void testMcpCatalogHasCorsOriginHeader() throws Exception {
+ handler.handleMcpCatalogRequest(mockRequest, mockResponse);
+ assertEquals("*", mockResponse.getHeader("Access-Control-Allow-Origin"));
+ }
+
+ public void testMcpCatalogHasCorsMethodsHeader() throws Exception {
+ handler.handleMcpCatalogRequest(mockRequest, mockResponse);
+ assertNotNull("CORS methods header must be set",
+ mockResponse.getHeader("Access-Control-Allow-Methods"));
+ }
+
+ public void testMcpCatalogHasCorsHeadersHeader() throws Exception {
+ handler.handleMcpCatalogRequest(mockRequest, mockResponse);
+ assertNotNull("CORS headers header must be set",
+ mockResponse.getHeader("Access-Control-Allow-Headers"));
+ }
+
+ // ── body ──────────────────────────────────────────────────────────────────
+
+ public void testMcpCatalogBodyIsValidJson() throws Exception {
+ handler.handleMcpCatalogRequest(mockRequest, mockResponse);
+ String body = mockResponse.getWriterContent();
+ assertNotNull("Response body must not be null", body);
+ assertFalse("Response body must not be empty", body.trim().isEmpty());
+ JsonNode root = MAPPER.readTree(body);
+ assertNotNull("Body must be parseable as JSON", root);
+ }
+
+ public void testMcpCatalogBodyHasToolsArray() throws Exception {
+ handler.handleMcpCatalogRequest(mockRequest, mockResponse);
+ JsonNode root = MAPPER.readTree(mockResponse.getWriterContent());
+ assertTrue("Body must have 'tools' key", root.has("tools"));
+ assertTrue("tools must be an array", root.get("tools").isArray());
+ }
+
+ // ── service discovery ─────────────────────────────────────────────────────
+
+ public void testMcpCatalogReflectsRegisteredService() throws Exception {
+ // Register a service and re-create the handler with the updated config
+ AxisConfiguration axisConfig = new AxisConfiguration();
+ AxisService svc = new AxisService("PaymentService");
+ AxisOperation op = new InOutAxisOperation();
+ op.setName(QName.valueOf("processPayment"));
+ svc.addOperation(op);
+ axisConfig.addService(svc);
+
+ ConfigurationContext configCtx = new ConfigurationContext(axisConfig);
+ SwaggerUIHandler h = new SwaggerUIHandler(configCtx);
+ MockHttpServletResponse resp = new MockHttpServletResponse();
+
+ h.handleMcpCatalogRequest(mockRequest, resp);
+
+ JsonNode tools = MAPPER.readTree(resp.getWriterContent()).path("tools");
+ assertTrue("At least one tool must be present", tools.size() > 0);
+
+ boolean found = false;
+ for (JsonNode tool : tools) {
+ if ("processPayment".equals(tool.path("name").asText())) {
+ found = true;
+ break;
+ }
+ }
+ assertTrue("processPayment tool must be in catalog", found);
+ }
+
+ // ── security headers (mirrors OpenAPI JSON endpoint) ─────────────────────
+
+ public void testMcpCatalogHasSecurityHeadersIfImplemented() throws Exception {
+ handler.handleMcpCatalogRequest(mockRequest, mockResponse);
+ // Cache-Control or X-Content-Type-Options may be set by the handler.
+ // We don't assert their exact values — just that the request completes
+ // successfully with a 200 status and valid JSON body.
+ assertEquals(200, mockResponse.getStatus());
+ JsonNode root = MAPPER.readTree(mockResponse.getWriterContent());
+ assertTrue(root.has("tools"));
+ }
+
+ // ── mocks ─────────────────────────────────────────────────────────────────
+
+ private static class MockHttpServletRequest implements HttpServletRequest {
+ @Override public String getScheme() { return "https"; }
+ @Override public String getServerName() { return "localhost"; }
+ @Override public int getServerPort() { return 8443; }
+ @Override public String getContextPath() { return "/axis2-json-api"; }
+
+ @Override public String getAuthType() { return null; }
+ @Override public Cookie[] getCookies() { return new Cookie[0]; }
+ @Override public long getDateHeader(String n) { return 0; }
+ @Override public String getHeader(String n) { return null; }
+ @Override public Enumeration<String> getHeaders(String n) { return null; }
+ @Override public Enumeration<String> getHeaderNames() { return null; }
+ @Override public int getIntHeader(String n) { return 0; }
+ @Override public String getMethod() { return "GET"; }
+ @Override public String getPathInfo() { return null; }
+ @Override public String getPathTranslated() { return null; }
+ @Override public String getQueryString() { return null; }
+ @Override public String getRemoteUser() { return null; }
+ @Override public boolean isUserInRole(String r) { return false; }
+ @Override public Principal getUserPrincipal() { return null; }
+ @Override public String getRequestedSessionId() { return null; }
+ @Override public String getRequestURI() { return "/axis2-json-api/openapi-mcp.json"; }
+ @Override public StringBuffer getRequestURL() { return new StringBuffer(); }
+ @Override public String getServletPath() { return ""; }
+ @Override public HttpSession getSession(boolean c) { return null; }
+ @Override public HttpSession getSession() { return null; }
+ @Override public String changeSessionId() { return null; }
+ @Override public boolean isRequestedSessionIdValid() { return false; }
+ @Override public boolean isRequestedSessionIdFromCookie() { return false; }
+ @Override public boolean isRequestedSessionIdFromURL() { return false; }
+ @Override public boolean authenticate(HttpServletResponse r) { return false; }
+ @Override public void login(String u, String p) { }
+ @Override public void logout() { }
+ @Override public Collection<Part> getParts() { return null; }
+ @Override public Part getPart(String n) { return null; }
+ @Override public <T extends HttpUpgradeHandler> T upgrade(Class<T> c) { return null; }
+ @Override public Object getAttribute(String n) { return null; }
+ @Override public Enumeration<String> getAttributeNames() { return null; }
+ @Override public String getCharacterEncoding() { return null; }
+ @Override public void setCharacterEncoding(String e) { }
+ @Override public int getContentLength() { return 0; }
+ @Override public long getContentLengthLong() { return 0; }
+ @Override public String getContentType() { return null; }
+ @Override public ServletInputStream getInputStream() { return null; }
+ @Override public String getParameter(String n) { return null; }
+ @Override public Enumeration<String> getParameterNames() { return null; }
+ @Override public String[] getParameterValues(String n) { return new String[0]; }
+ @Override public Map<String, String[]> getParameterMap() { return null; }
+ @Override public String getProtocol() { return "HTTP/2"; }
+ @Override public String getRemoteAddr() { return "127.0.0.1"; }
+ @Override public String getRemoteHost() { return "localhost"; }
+ @Override public void setAttribute(String n, Object o) { }
+ @Override public void removeAttribute(String n) { }
+ @Override public Locale getLocale() { return Locale.US; }
+ @Override public Enumeration<Locale> getLocales() { return null; }
+ @Override public boolean isSecure() { return true; }
+ @Override public RequestDispatcher getRequestDispatcher(String p) { return null; }
+ @Override public int getRemotePort() { return 0; }
+ @Override public String getLocalName() { return "localhost"; }
+ @Override public String getLocalAddr() { return "127.0.0.1"; }
+ @Override public int getLocalPort() { return 8443; }
+ @Override public ServletContext getServletContext() { return null; }
+ @Override public AsyncContext startAsync() { return null; }
+ @Override public AsyncContext startAsync(ServletRequest q, ServletResponse s) { return null; }
+ @Override public boolean isAsyncStarted() { return false; }
+ @Override public boolean isAsyncSupported() { return false; }
+ @Override public AsyncContext getAsyncContext() { return null; }
+ @Override public DispatcherType getDispatcherType() { return null; }
+ @Override public BufferedReader getReader() { return null; }
+ @Override public jakarta.servlet.ServletConnection getServletConnection() { return null; }
+ @Override public String getProtocolRequestId() { return null; }
+ @Override public String getRequestId() { return null; }
+ }
+
+ private static class MockHttpServletResponse implements HttpServletResponse {
+ private String contentType;
+ private int status = 0;
+ private final StringWriter writer = new StringWriter();
+ private final PrintWriter printWriter = new PrintWriter(writer);
+ private final Map<String, String> headers = new HashMap<>();
+
+ public String getWriterContent() { return writer.toString(); }
+
+ @Override public void setContentType(String t) { this.contentType = t; }
+ @Override public String getContentType() { return contentType; }
+ @Override public void setStatus(int sc) { this.status = sc; }
+ @Override public int getStatus() { return status; }
+ @Override public PrintWriter getWriter() { return printWriter; }
+ @Override public void setHeader(String n, String v) { headers.put(n, v); }
+ @Override public String getHeader(String n) { return headers.get(n); }
+ @Override public Collection<String> getHeaders(String n) { return null; }
+ @Override public Collection<String> getHeaderNames() { return headers.keySet(); }
+ @Override public boolean containsHeader(String n) { return headers.containsKey(n); }
+
+ @Override public void addCookie(Cookie c) { }
+ @Override public String encodeURL(String u) { return u; }
+ @Override public String encodeRedirectURL(String u) { return u; }
+ @Override public void sendError(int sc, String m) { this.status = sc; }
+ @Override public void sendError(int sc) { this.status = sc; }
+ @Override public void sendRedirect(String l) { }
+ @Override public void sendRedirect(String l, int sc, boolean cb) { }
+ @Override public void setDateHeader(String n, long d) { }
+ @Override public void addDateHeader(String n, long d) { }
+ @Override public void addHeader(String n, String v) { headers.put(n, v); }
+ @Override public void setIntHeader(String n, int v) { }
+ @Override public void addIntHeader(String n, int v) { }
+ @Override public String getCharacterEncoding() { return "UTF-8"; }
+ @Override public ServletOutputStream getOutputStream() { return null; }
+ @Override public void setCharacterEncoding(String c) { }
+ @Override public void setContentLength(int l) { }
+ @Override public void setContentLengthLong(long l) { }
+ @Override public void setBufferSize(int s) { }
+ @Override public int getBufferSize() { return 0; }
+ @Override public void flushBuffer() { }
+ @Override public void resetBuffer() { }
+ @Override public boolean isCommitted() { return false; }
+ @Override public void reset() { }
+ @Override public void setLocale(Locale l) { }
+ @Override public Locale getLocale() { return null; }
+ }
+}
diff --git a/modules/samples/userguide/src/userguide/springbootdemo-tomcat11/src/main/java/userguide/springboot/Axis2Application.java b/modules/samples/userguide/src/userguide/springbootdemo-tomcat11/src/main/java/userguide/springboot/Axis2Application.java
index f378e7ddad..a5878ba523 100644
--- a/modules/samples/userguide/src/userguide/springbootdemo-tomcat11/src/main/java/userguide/springboot/Axis2Application.java
+++ b/modules/samples/userguide/src/userguide/springbootdemo-tomcat11/src/main/java/userguide/springboot/Axis2Application.java
@@ -96,6 +96,7 @@ import userguide.springboot.security.webservices.JWTAuthenticationProvider;
import userguide.springboot.security.webservices.HTTPPostOnlyRejectionFilter;
import userguide.springboot.security.webservices.RequestAndResponseValidatorFilter;
import userguide.springboot.security.webservices.RestAuthenticationEntryPoint;
+import userguide.springboot.security.webservices.X509AuthenticationFilter;
@SpringBootApplication(exclude = {
DataSourceAutoConfiguration.class,
@@ -347,9 +348,37 @@ public class Axis2Application extends SpringBootServletInitializer {
return headerFilter;
}
- // OpenAPI documentation endpoints — GET requests, no auth required
+ // mTLS requests arrive on port 8443; Tomcat enforces certificateVerification=required
+ // so any request reaching this matcher has already passed the TLS client cert check.
+ class MtlsRequestMatcher implements RequestMatcher {
+ @Override
+ public boolean matches(HttpServletRequest request) {
+ return request.getLocalPort() == 8443;
+ }
+ }
+
+ @Bean
+ public X509AuthenticationFilter x509AuthenticationFilter() {
+ return new X509AuthenticationFilter();
+ }
+
+ @Bean(name = "springSecurityFilterChainMtls")
+ @Order(2)
+ public SecurityFilterChain springSecurityFilterChainMtls() throws Exception {
+ // No JWT, no POST-only restriction. X509 filter sets authentication from the
+ // client cert; filterSecurityInterceptor passes any authenticated principal.
+ return new DefaultSecurityFilterChain(
+ new MtlsRequestMatcher(),
+ headerWriterFilter(),
+ x509AuthenticationFilter(),
+ requestAndResponseValidatorFilter(),
+ sessionManagementFilter(),
+ filterSecurityInterceptor());
+ }
+
+ // OpenAPI documentation endpoints — GET requests, no auth required (plain HTTP fallback)
class OpenApiRequestMatcher implements RequestMatcher {
- private static final String[] OPENAPI_PATHS = {"/openapi.json", "/openapi.yaml", "/swagger-ui"};
+ private static final String[] OPENAPI_PATHS = {"/openapi.json", "/openapi.yaml", "/swagger-ui", "/openapi-mcp.json"};
@Override
public boolean matches(HttpServletRequest request) {
@@ -364,7 +393,7 @@ public class Axis2Application extends SpringBootServletInitializer {
}
@Bean(name = "springSecurityFilterChainOpenApi")
- @Order(2)
+ @Order(3)
public SecurityFilterChain springSecurityFilterChainOpenApi() throws Exception {
// Only header filter — no POST restriction, no JWT, no login processing
return new DefaultSecurityFilterChain(new OpenApiRequestMatcher(), headerWriterFilter());
@@ -374,7 +403,7 @@ public class Axis2Application extends SpringBootServletInitializer {
// A login url will match, otherwise invoke jwtAuthenticationFilter
@Bean(name = "springSecurityFilterChainLogin")
- @Order(3)
+ @Order(4)
public SecurityFilterChain springSecurityFilterChainLogin() throws ServletException, Exception {
String logPrefix = "GenericAccessDecisionManager.springSecurityFilterChain , ";
logger.debug(logPrefix + "inside main filter config ...");
diff --git a/modules/samples/userguide/src/userguide/springbootdemo-tomcat11/src/main/java/userguide/springboot/configuration/Axis2WebAppInitializer.java b/modules/samples/userguide/src/userguide/springbootdemo-tomcat11/src/main/java/userguide/springboot/configuration/Axis2WebAppInitializer.java
index c7615aefe3..2bae0d74fe 100644
--- a/modules/samples/userguide/src/userguide/springbootdemo-tomcat11/src/main/java/userguide/springboot/configuration/Axis2WebAppInitializer.java
+++ b/modules/samples/userguide/src/userguide/springbootdemo-tomcat11/src/main/java/userguide/springboot/configuration/Axis2WebAppInitializer.java
@@ -60,8 +60,8 @@ public class Axis2WebAppInitializer implements ServletContextInitializer {
ServletRegistration.Dynamic openApi = container.addServlet(
"OpenApiServlet", new OpenApiServlet());
openApi.setLoadOnStartup(2);
- openApi.addMapping("/openapi.json", "/openapi.yaml", "/swagger-ui");
- logger.warn("OpenApiServlet registered at /openapi.json, /openapi.yaml, /swagger-ui");
+ openApi.addMapping("/openapi.json", "/openapi.yaml", "/swagger-ui", "/openapi-mcp.json");
+ logger.warn("OpenApiServlet registered at /openapi.json, /openapi.yaml, /swagger-ui, /openapi-mcp.json");
}
private void addAxis2Servlet(ServletContext container, AnnotationConfigWebApplicationContext ctx) {
diff --git a/modules/samples/userguide/src/userguide/springbootdemo-tomcat11/src/main/java/userguide/springboot/configuration/OpenApiServlet.java b/modules/samples/userguide/src/userguide/springbootdemo-tomcat11/src/main/java/userguide/springboot/configuration/OpenApiServlet.java
index 623efe3c2e..7e293e9f90 100644
--- a/modules/samples/userguide/src/userguide/springbootdemo-tomcat11/src/main/java/userguide/springboot/configuration/OpenApiServlet.java
+++ b/modules/samples/userguide/src/userguide/springbootdemo-tomcat11/src/main/java/userguide/springboot/configuration/OpenApiServlet.java
@@ -70,6 +70,8 @@ public class OpenApiServlet extends HttpServlet {
handler.handleOpenApiYamlRequest(request, response);
} else if (uri.endsWith("/swagger-ui") || uri.contains("/swagger-ui/")) {
handler.handleSwaggerUIRequest(request, response);
+ } else if (uri.endsWith("/openapi-mcp.json")) {
+ handler.handleMcpCatalogRequest(request, response);
} else {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
diff --git a/modules/samples/userguide/src/userguide/springbootdemo-tomcat11/src/main/java/userguide/springboot/security/webservices/X509AuthenticationFilter.java b/modules/samples/userguide/src/userguide/springbootdemo-tomcat11/src/main/java/userguide/springboot/security/webservices/X509AuthenticationFilter.java
new file mode 100644
index 0000000000..a1c96e1af1
--- /dev/null
+++ b/modules/samples/userguide/src/userguide/springbootdemo-tomcat11/src/main/java/userguide/springboot/security/webservices/X509AuthenticationFilter.java
@@ -0,0 +1,111 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package userguide.springboot.security.webservices;
+
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.ServletRequest;
+import jakarta.servlet.ServletResponse;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.web.filter.GenericFilterBean;
+
+import javax.security.auth.x500.X500Principal;
+import java.io.IOException;
+import java.security.cert.X509Certificate;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * Authenticates requests that arrive over a Tomcat mTLS connector.
+ *
+ * <p>Tomcat enforces {@code certificateVerification="required"} at the TLS
+ * handshake — only clients presenting a certificate signed by the configured
+ * CA reach this filter. This filter reads the already-verified certificate
+ * from the Servlet request attribute and creates an authenticated
+ * {@link SecurityContextHolder} entry so downstream filters and the
+ * {@code FilterSecurityInterceptor} see an authenticated principal.
+ *
+ * <p>The client CN (e.g. {@code axis2-mcp-bridge}) becomes the principal
+ * name. The single granted authority is {@code ROLE_X509_CLIENT}.
+ */
+public class X509AuthenticationFilter extends GenericFilterBean {
+
+ private static final Logger logger = LogManager.getLogger(X509AuthenticationFilter.class);
+
+ /** Servlet attribute name Tomcat uses to expose the verified client cert chain. */
+ private static final String CERT_ATTRIBUTE = "jakarta.servlet.request.X509Certificate";
+
+ @Override
+ public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
+ FilterChain chain) throws IOException, ServletException {
+
+ HttpServletRequest request = (HttpServletRequest) servletRequest;
+
+ X509Certificate[] certs = (X509Certificate[]) request.getAttribute(CERT_ATTRIBUTE);
+
+ if (certs != null && certs.length > 0) {
+ X509Certificate clientCert = certs[0];
+ String cn = extractCN(clientCert.getSubjectX500Principal());
+
+ List<GrantedAuthority> authorities =
+ Collections.singletonList(new SimpleGrantedAuthority("ROLE_X509_CLIENT"));
+
+ UsernamePasswordAuthenticationToken auth =
+ new UsernamePasswordAuthenticationToken(cn, clientCert, authorities);
+
+ SecurityContextHolder.getContext().setAuthentication(auth);
+ request.setAttribute("x509_cn", cn);
+
+ logger.debug("X509AuthenticationFilter: authenticated CN=" + cn
+ + " on port " + request.getLocalPort());
+ } else {
+ // Tomcat certificateVerification=required means this should not happen on 8443,
+ // but log it defensively in case the connector config changes.
+ logger.warn("X509AuthenticationFilter: no client cert on port "
+ + request.getLocalPort() + " — no authentication set");
+ }
+
+ chain.doFilter(servletRequest, servletResponse);
+ }
+
+ /**
+ * Extracts the CN value from an {@link X500Principal}.
+ *
+ * <p>Uses RFC 2253 format ({@code CN=value,O=...}) for reliable parsing.
+ * Returns the full DN string if no CN attribute is present.
+ */
+ private String extractCN(X500Principal principal) {
+ String dn = principal.getName(X500Principal.RFC2253);
+ for (String part : dn.split(",")) {
+ part = part.trim();
+ if (part.startsWith("CN=")) {
+ return part.substring(3);
+ }
+ }
+ return dn;
+ }
+}