Your agent's tools live inside one app, and a second app must copy them. Move them behind an MCP server, test it, connect your agent and lock it down.
You need the Part 6 project, a JDK, Docker and Ollama.
MCP in plain words
MCP, the Model Context Protocol, is a standard way for an AI app to use tools and data. Write a tool once, and any client that speaks the protocol can call it.
The specification names three roles. A host is the AI app, a client is its connector, and a server offers features:
| Feature | What it is |
|---|---|
| Tools | Functions the model may ask to run |
| Resources | Data for the user or the model to read |
| Prompts | Message templates |
Messages use JSON-RPC, a small format for calling a method by name.
What changed on 2026-07-28
The changelog calls the protocol stateless. In practice:
- The
initializehandshake and protocol sessions are gone. - Every request carries its protocol version and client capabilities in a
_metablock. - Servers must answer
server/discover, which lists versions and capabilities. Clients may call it. - Over HTTP, requests need headers such as
Mcp-Method. - Optional extensions add features, such as long-running Tasks and interactive MCP Apps. Both sides must support them.
- Roots, Sampling and Logging are deprecated.
Pick your transport and protocol
A transport is how messages travel. STDIO runs a server as a child process. Ours is a web service, so we chose Streamable HTTP.
We used the webmvc server starter, not webflux. One property picks the protocol:
spring.ai.mcp.server.protocol | Meaning |
|---|---|
STREAMABLE (default) | Earlier revisions, with a session |
STATELESS | Earlier revisions, no session |
SSE | Old transport, deprecated |
MODERN | The 2026-07-28 revision |
STDIO is switched on with spring.ai.mcp.server.stdio=true. We did not test STDIO, SSE or WebFlux.
We sent three requests to three settings:
| Setting | Old-style initialize | 2026-07-28 tools/list | Request with a browser Origin |
|---|---|---|---|
MODERN | 400, refused | 200 | 403 |
STATELESS | 200 | 200 | 200 |
STREAMABLE | 200, with a session ID | 400 | 200 |
The older client's refusal looked like this:
{"jsonrpc":"2.0","id":1,"error":{"code":-32020,"message":"Missing required header: Mcp-Method"}}
A request that named the old version got -32022, with "supported":["2026-07-28"].
We chose MODERN, so older clients cannot use this server. The release post says support for both at once is being explored.
The modern server page says your @McpTool beans are served unchanged. Methods that ask for a session context are skipped.
Create the MCP server
The project now looks like this:
finished/
ticket-mcp-server/ tools, resource, security, ingest job, docs/
assistant/ the agent, now an MCP client
db/01-roles.sql the read-only database role
tools/DevAuth.java makes local keys and tokens
The server module's key dependencies:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-mcp-server-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security-oauth2-resource-server</artifactId>
</dependency>
It keeps Part 5's search dependencies too.
server.address=127.0.0.1
server.port=8090
# ----- MCP: the 2026-07-28 revision, over Streamable HTTP -----
spring.ai.mcp.server.protocol=MODERN
spring.ai.mcp.server.name=ticket-mcp-server
spring.ai.mcp.server.version=1.0.0
spring.ai.mcp.server.instructions=Read-only access to Lumen Board support tickets and product documents.
spring.ai.mcp.server.modern.mcp-endpoint=/mcp
# Our requests are tiny. The default limit is 16MB.
spring.ai.mcp.server.modern.max-request-size=64KB
The database settings use the read-only role, which we set up in the security section:
# ----- Data: a database role that can only read -----
spring.datasource.url=jdbc:postgresql://localhost:5442/lumen
spring.datasource.username=ticket_reader
spring.datasource.password=ticket_reader
spring.ai.vectorstore.pgvector.initialize-schema=false
spring.ai.vectorstore.pgvector.index-type=HNSW
spring.ai.vectorstore.pgvector.distance-type=COSINE_DISTANCE
spring.ai.vectorstore.pgvector.dimensions=1024
# The server makes vectors for searches. It talks to no chat model.
spring.ai.model.chat=none
spring.ai.ollama.embedding.model=mxbai-embed-large
The tools
The ticket tools moved almost unchanged from Part 6. They return small records, with no email field:
/** What a client gets back for one ticket. No email address. */
record TicketView(String id, String customerId, String subject, String status, String opened, String body) { }
/** One line of a ticket list. No body, so the list stays small. */
record TicketLine(String id, String subject, String status, String opened) { }
record TicketResult(String problem, TicketView ticket) { }
record TicketListResult(String problem, List<TicketLine> tickets) { }
The annotations are new:
@McpTool(name = "get_ticket",
description = "Read one support ticket: subject, text, status and customer id.",
annotations = @McpTool.McpAnnotations(readOnlyHint = true, destructiveHint = false, openWorldHint = false))
TicketResult getTicket(
@McpToolParam(description = "Ticket id: T- and four digits, for example T-1001") String ticketId,
McpMeta meta) {
return audit.record("get_ticket", Map.of("ticketId", String.valueOf(ticketId), "scope", scopeOf(meta)), () -> {
if (ticketId == null || !TICKET_ID.matcher(ticketId).matches()) {
return new TicketResult("ticketId must look like T-1001.", null);
}
// "Not found" and "not yours" read the same, so the answer leaks nothing.
return store.find(ticketId)
.filter(t -> inScope(meta, t.customerId()))
.map(t -> new TicketResult(null, new TicketView(t.id(), t.customerId(), t.subject(),
t.status(), t.opened().toString(), Text.shorten(t.body(), MAX_BODY))))
.orElseGet(() -> new TicketResult("No ticket with that id for this customer.", null));
});
}
@McpTooland@McpToolParamcome fromorg.springframework.ai.mcp.annotation.readOnlyHinttells clients the tool changes nothing. The spec says to treat such hints as untrusted unless you trust the server.McpMetareceives the request's_meta. It is not in the schema.audit.recordlogs the call.
Part 6 hid other customers' tickets with a ToolContext. Across a network, the client sends the customer ID in _meta:
/**
* The scope can only narrow what the caller's token already allows. A call without it sees every
* customer, because the token says this caller may. The model cannot set _meta.
*/
static boolean inScope(McpMeta meta, String customerId) {
String scope = scopeOf(meta);
return scope.equals("all") || scope.equals(customerId);
}
/** The customer the client narrowed the call to, or "all". */
private static String scopeOf(McpMeta meta) {
Object scope = meta == null ? null : meta.get(CUSTOMER_SCOPE);
return scope == null ? "all" : String.valueOf(scope);
}
The list tool follows the same pattern:
@McpTool(name = "list_customer_tickets",
description = "List up to 5 recent tickets of one customer: id, subject, status, date. No ticket text.",
annotations = @McpTool.McpAnnotations(readOnlyHint = true, destructiveHint = false, openWorldHint = false))
TicketListResult listCustomerTickets(
@McpToolParam(description = "Customer id: C- and three digits, for example C-101") String customerId,
McpMeta meta) {
return audit.record("list_customer_tickets", Map.of("customerId", String.valueOf(customerId), "scope", scopeOf(meta)), () -> {
if (customerId == null || !CUSTOMER_ID.matcher(customerId).matches()) {
return new TicketListResult("customerId must look like C-101.", List.of());
}
if (!inScope(meta, customerId)) {
return new TicketListResult("You can only list tickets of this ticket's customer.", List.of());
}
var lines = store.recentFor(customerId, MAX_TICKETS).stream()
.map(t -> new TicketLine(t.id(), t.subject(), t.status(), t.opened().toString()))
.toList();
return new TicketListResult(lines.isEmpty() ? "No tickets for that customer." : null, lines);
});
}
The search tool and one resource sit in a second class:
@McpTool(name = "search_docs",
description = "Search the Lumen Board product documents. Use it before you state any product fact.",
annotations = @McpTool.McpAnnotations(readOnlyHint = true, destructiveHint = false, openWorldHint = false))
DocResult searchDocs(@McpToolParam(description = "A short question about the product, in plain words") String query) {
return audit.record("search_docs", Map.of("query", String.valueOf(query)), () -> {
if (query == null || query.isBlank() || query.length() > MAX_QUERY) {
return new DocResult("query must be 1 to " + MAX_QUERY + " characters.", List.of());
}
var passages = search.search(query, MAX_PASSAGES, null).stream()
.filter(p -> p.score() >= minScore)
.map(p -> new DocPassage(p.source(), Text.shorten(p.text(), MAX_TEXT)))
.toList();
return new DocResult(passages.isEmpty() ? "No matching passage in the documents." : null, passages);
});
}
@McpResource(uri = "tickets://categories", name = "ticket-categories", mimeType = "text/plain",
description = "The ticket categories, one per line. They match the document folders.")
String categories() {
return "billing\nboards\nintegrations\nsecurity";
}
Run it
The ingest job is a profile. It starts no web server and signs in as the owner:
spring.main.web-application-type=none
spring.datasource.username=lumen
spring.datasource.password=lumen
spring.ai.vectorstore.pgvector.initialize-schema=true
Compose runs the role script once, on a new volume, and listens only locally:
ports:
- "127.0.0.1:5442:5432"
volumes:
- lumen-data:/var/lib/postgresql
- ./db:/docker-entrypoint-initdb.d:ro
docker compose up -d --wait
java tools/DevAuth.java keys
./mvnw package -DskipTests
(cd ticket-mcp-server && java -jar target/ticket-mcp-server-0.0.1-SNAPSHOT.jar --spring.profiles.active=ingest)
(cd ticket-mcp-server && java -jar target/ticket-mcp-server-0.0.1-SNAPSHOT.jar)
The ingest job printed IngestReport[files=8, chunks=37, rowsInStore=37]. The server's log, trimmed:
McpServerModernAutoConfiguration : Registered modern tools: 3
McpServerModernAutoConfiguration : Registered modern resources: 1, resource templates: 0
McpServerModernAutoConfiguration : Registered modern prompts: 0
Tomcat started on port 8090 (http) with context path '/'
Look before you trust it
Make a token and send one raw request, with no AI involved:
export MCP_TOKEN=$(java tools/DevAuth.java token --minutes 600)
curl -i http://127.0.0.1:8090/mcp \
-H "Authorization: Bearer $MCP_TOKEN" \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-H "MCP-Protocol-Version: 2026-07-28" \
-H "Mcp-Method: tools/list" \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}'
The reply was HTTP/1.1 200, and the body began like this:
{"jsonrpc":"2.0","id":1,"result":{"tools":[{"name":"get_ticket","title":"get_ticket","description":"Read one support ticket: subject, text, status and customer id.","inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"ticketId":{"type":"string","description":"Ticket id: T- and four digits, for example T-1001"}},"required":["ticketId"]},"annotations":{"title":"","readOnlyHint":true,"destructiveHint":false,"idempotentHint":false,"openWorldHint":false}}, ...],"ttlMs":0,"cacheScope":"private","resultType":"complete","_meta":{"io.modelcontextprotocol/serverInfo":{"name":"ticket-mcp-server","version":"1.0.0"}}}}
| Field | What it means |
|---|---|
MCP-Protocol-Version | The revision this request uses. It must match the one in _meta |
Mcp-Method | Repeats the method in a header. Without it we got error -32020 |
_meta | Version and capabilities, sent every time. There is no session to remember them |
inputSchema | JSON Schema for the arguments. The model reads it to build a call |
annotations | Hints about behaviour. They enforce nothing |
ttlMs, cacheScope | How long, and for whom, the list may be cached. Zero means ask again |
resultType | complete, or a request for more input |
The MCP Inspector
The Inspector is the reference testing tool. It has a web page, a terminal view and a command line mode:
npx @modelcontextprotocol/inspector --cli http://127.0.0.1:8090/mcp --transport http \
--protocol-era modern --header "Authorization: Bearer $MCP_TOKEN" \
--method tools/call --tool-name get_ticket --tool-arg ticketId=T-1003
Its output, trimmed:
"content": [
{
"type": "text",
"text": "{\"problem\":null,\"ticket\":{\"id\":\"T-1003\",\"customerId\":\"C-102\",\"subject\":\"Webhook was switched off\", ...
}
],
"isError": false
Reading the resource works the same way, with --method resources/read --uri tickets://categories:
"contents": [
{
"uri": "tickets://categories",
"mimeType": "text/plain",
"text": "billing
boards
integrations
security"
}
],
"ttlMs": 0,
"cacheScope": "private"
We used version 2.17.0. Its package asks for Node 24.22.1 or newer on the 24 line. It ran on our 24.16.0, but use a supported version. With --protocol-era legacy, the same command failed with Missing required header: Mcp-Method.
Connect the agent as a client
Remove the local tool classes. Add spring-ai-starter-mcp-client, then describe the server:
spring.ai.mcp.client.streamable-http.connections.tickets.url=http://127.0.0.1:8090
spring.ai.mcp.client.streamable-http.connections.tickets.protocol=MODERN
# This app calls the server under one identity, so one client serves every request.
spring.ai.mcp.client.streamable-http.connections.tickets.client-scope=SHARED
spring.ai.mcp.client.request-timeout=30s
# A signed token for the server. Keep it out of this file: set the MCP_TOKEN environment variable.
app.mcp.token=${MCP_TOKEN:}
# The whole allowlist. A tool the server adds later is not offered to the model until it is named here.
app.mcp.allowed-tools=get_ticket,list_customer_tickets,search_docs
In Spring AI 2.1.0, a modern client connection uses Streamable HTTP on the JDK client. The release post plans STDIO and WebClient transports for 2.1.1 in December.
protocol=MODERN is required, because a connection is legacy by default. The default client-scope is PER_REQUEST. Our app has one identity, so we use SHARED.
Our code adds two things to each request, and keeps the tool names simple:
@Bean
McpHttpRequestCustomizer bearerToken(@Value("${app.mcp.token:}") String token) {
return McpHttpRequestCustomizer.fromSync((request, headers, context) -> {
if (!token.isBlank()) {
headers.set("Authorization", "Bearer " + token);
}
});
}
/**
* Without this bean, Spring AI would copy the whole tool context into the request. We send one
* value: the customer, so the server can narrow what this call may see.
*/
@Bean
ToolContextToMcpMetaConverter customerScopeOnly() {
return context -> {
AgentRun run = context == null ? null : AgentRun.from(context);
return run == null || run.customerId() == null
? Map.of()
: Map.of("com.example/customerId", run.customerId());
};
}
/**
* A modern connection names tools after the connection, for example tickets_get_ticket. We use one
* server, so we keep the server's names. With two servers, keep the prefix.
*/
@Bean
McpModernToolNamePrefixGenerator serverToolNames() {
return McpModernToolNamePrefixGenerator.noPrefix();
}
Without the last bean, our first run answered 503: tools arrived as tickets_get_ticket. The client page does say so.
MCP tools arrive as ordinary ToolCallbacks. We filter them:
List<ToolCallback> tools() {
List<ToolCallback> offered;
try {
offered = providers.orderedStream()
.flatMap(provider -> Arrays.stream(provider.getToolCallbacks()))
.toList();
} catch (McpClientException e) {
// For example HTTP 401: the server answered and refused our token.
log.warn("the ticket server refused the request: {}", e.getMessage());
throw new TicketServerUnavailableException("the ticket server refused the request");
}
List<ToolCallback> tools = offered.stream()
.filter(tool -> allowed.contains(tool.getToolDefinition().name()))
.sorted(Comparator.comparing(tool -> tool.getToolDefinition().name()))
.<ToolCallback>map(LoggedToolCallback::new)
.toList();
if (tools.size() != allowed.size()) {
var found = tools.stream().map(tool -> tool.getToolDefinition().name()).toList();
log.warn("expected tools {} from the ticket server, got {}", allowed, found);
throw new TicketServerUnavailableException("the ticket server did not offer every allowed tool");
}
return tools;
}
Missing tools stop the run, and a test holds us to it:
@Test
void noTicketServerIs503() throws Exception {
when(server.tools()).thenThrow(new TicketServerUnavailableException("down"));
postJson("/agent/draft", "{\"ticketId\":\"T-1001\"}").andExpect(status().isServiceUnavailable());
}
An agent with no tools would still write a confident answer.
Part 6's tools recorded which tickets and sources they used. Now the app reads that from each result:
static void record(String result, AgentRun run) {
JsonNode body = body(result);
if (body == null) {
return;
}
add(body.path("ticket").path("id"), run::usedTicket);
body.path("tickets").forEach(line -> add(line.path("id"), run::usedTicket));
body.path("passages").forEach(passage -> add(passage.path("source"), run::usedSource));
}
Before the loop starts, our code asks who owns the ticket:
/**
* Our own code asks the server who the ticket belongs to, before the model sees anything. The
* answer sets the scope for every later call of this run.
*/
private static String customerOf(String ticketId, List<ToolCallback> tools) {
ToolCallback getTicket = tools.stream()
.filter(tool -> tool.getToolDefinition().name().equals("get_ticket"))
.findFirst()
.orElseThrow();
// The controller has already checked the id's format, so it is safe to put in JSON.
var context = new ToolContext(new AgentRun("lookup", null).asToolContext());
String result = getTicket.call("{\"ticketId\":\"" + ticketId + "\"}", context);
var body = ToolResults.body(result);
if (body == null || !body.path("ticket").path("customerId").isString()) {
throw new UnknownTicketException();
}
return body.path("ticket").path("customerId").asString();
}
The rest matches Part 6.
Three questions, now over MCP
(cd assistant && java -jar target/assistant-0.0.1-SNAPSHOT.jar)
curl -X POST localhost:8080/agent/draft -H "Content-Type: application/json" -d '{"ticketId":"T-1001"}'
We asked about T-1001, T-1003 and T-1004. In our test run (Spring AI 2.1.0, MCP Java SDK 2.2.0, MCP revision 2026-07-28, 2026-11-29) each ended DRAFTED after 3 model calls. The agent's log for the first, trimmed:
agent.tools : tool=get_ticket args={"ticketId":"T-1001"} resultChars=337 ms=138
agent.loop : modelCall=1 asksFor=[get_ticket] tokens=733 tokensSoFar=733 ms=38717
agent.tools : tool=get_ticket args={"ticketId":"T-1001"} resultChars=337 ms=62
agent.loop : modelCall=2 asksFor=[search_docs] tokens=873 tokensSoFar=1606 ms=8760
agent.tools : tool=search_docs args={"query":"<23 chars>"} resultChars=883 ms=5582
agent.run : outcome=DRAFTED detail=null modelCalls=3 tools=[get_ticket, search_docs] sources=[billing/plans.md, billing/cancellation.md] warnings=[]
The server saw the same calls. These lines prove they travelled through MCP:
[caller=ticket-assistant] mcp.audit : tool=get_ticket args={scope=all, ticketId=T-1001} resultChars=296 ms=3
[caller=ticket-assistant] mcp.audit : tool=get_ticket args={scope=C-101, ticketId=T-1001} resultChars=296 ms=0
[caller=ticket-assistant] mcp.audit : tool=search_docs args={query=<23 chars>} resultChars=842 ms=5515
The first get_ticket is ours. After it, every ticket call is narrowed to that customer. The response has the same shape as in Part 6:
{"requestId":"96f63574","outcome":"DRAFTED","draftId":"40ff72ee-d0c0-45cf-b6a2-5ceae53d96aa","draft":"Our webhook was switched off after five consecutive failures. ...","toolsCalled":["get_ticket","search_docs"],"ticketsUsed":["T-1003"],"sourcesUsed":["integrations/api-and-webhooks.md"],"warnings":[],"modelCalls":3,"tokens":2721,"detail":null}
Optional: a second client
Claude Code is a different product from your agent. It shows the server works with a client you did not write.
The Claude Code MCP docs give the command for a remote HTTP server. The default scope is local: private to you, in this project.
claude mcp add --transport http lumen-tickets http://127.0.0.1:8090/mcp \
--header "Authorization: Bearer $MCP_TOKEN"
claude mcp list
claude -p "Use the get_ticket tool from lumen-tickets to read ticket T-1008. Say in one sentence what the customer wants." \
--allowedTools "mcp__lumen-tickets__get_ticket"
claude mcp remove lumen-tickets -s local
With Claude Code 2.1.332 the list marked the server as connected, and the prompt answered:
The customer wants to recover a planning board that a colleague accidentally deleted (twelve days before the ticket was opened on 2026-11-25).
The server logged get_ticket for ticketId=T-1008 with scope=all. Claude Code sent no customer scope, so the token's rights decided. The command stores your token in Claude Code's settings, so remove the server when you finish.
Security
HTTP MCP servers start open. The server page says the starters add no authentication, even on localhost.
1. Who may call
The specification makes authorization optional. When an HTTP server supports it, it acts as an OAuth resource server: it checks an access token on every request.
@Bean
SecurityFilterChain mcpSecurity(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(requests -> requests
.requestMatchers("/mcp").hasAuthority("SCOPE_tickets:read")
.anyRequest().denyAll())
.oauth2ResourceServer(oauth -> oauth.jwt(Customizer.withDefaults()))
// No cookies and no server session, so there is nothing for a forged form post to ride on.
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.csrf(csrf -> csrf.disable())
.build();
}
spring.security.oauth2.resourceserver.jwt.public-key-location=file:${app.auth.public-key:../keys/public.pem}
spring.security.oauth2.resourceserver.jwt.audiences=http://127.0.0.1:8090/mcp
The audience names the server a token was made for. The spec says a server must refuse tokens made for anyone else.
We tested a stand-in: DevAuth signs tokens with a key on your disk. We ran no OAuth login flow. In production, use your authorization server.
Making the keys takes a few lines:
private static void keys() throws Exception {
var generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048);
var pair = generator.generateKeyPair();
Files.createDirectories(KEYS);
Files.writeString(KEYS.resolve("private.pem"), pem("PRIVATE KEY", pair.getPrivate().getEncoded()));
Files.writeString(KEYS.resolve("public.pem"), pem("PUBLIC KEY", pair.getPublic().getEncoded()));
System.out.println("Wrote keys/private.pem and keys/public.pem. Never commit them.");
}
Our stand-in then signs these claims:
long now = Instant.now().getEpochSecond();
long expires = now + 60 * Long.parseLong(options.getOrDefault("--minutes", "60"));
String header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}";
String claims = "{\"sub\":\"%s\",\"aud\":\"%s\",\"scope\":\"%s\",\"iat\":%d,\"exp\":%d}".formatted(
options.getOrDefault("--sub", "ticket-assistant"),
options.getOrDefault("--audience", "http://127.0.0.1:8090/mcp"),
options.getOrDefault("--scope", "tickets:read"),
now, expires);
A request with no token got:
HTTP/1.1 401
WWW-Authenticate: Bearer resource_metadata="http://127.0.0.1:8090/.well-known/oauth-protected-resource"
Spring Security published that page. It lists no authorization server.
2. Least privilege
The server signs in to Postgres as a role that starts with nothing:
create role ticket_reader login password 'ticket_reader';
grant connect on database lumen to ticket_reader;
grant usage on schema public to ticket_reader;
The ingest job, which runs as the owner, grants one right:
@Bean
ApplicationRunner ingest(DocumentIngestor ingestor, JdbcTemplate jdbc) {
return args -> {
System.out.println(ingestor.ingestAll());
// The server's role gets exactly one right: reading this table.
jdbc.execute("grant select on vector_store to ticket_reader");
};
}
docker compose exec -e PGPASSWORD=ticket_reader db psql -h 127.0.0.1 -U ticket_reader -d lumen -c "delete from vector_store"
ERROR: permission denied for table vector_store
ReaderRoleIT keeps it that way. It starts a container with our role script:
static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer(
DockerImageName.parse("pgvector/pgvector:0.8.7-pg18").asCompatibleSubstituteFor("postgres"))
.withDatabaseName("lumen")
.withUsername("lumen")
.withCopyFileToContainer(MountableFile.forHostPath("../db/01-roles.sql"),
"/docker-entrypoint-initdb.d/01-roles.sql");
Then it tries to misuse the role:
try (Connection reader = connect("ticket_reader", "ticket_reader")) {
assertThat(reader.createStatement().executeQuery("select count(*) from vector_store").next()).isTrue();
assertDenied(reader, "insert into vector_store values ('planted')");
assertDenied(reader, "delete from vector_store");
assertDenied(reader, "select * from reply_draft");
assertDenied(reader, "create table mine (x int)");
}
private static void assertDenied(Connection connection, String sql) {
assertThatThrownBy(() -> connection.createStatement().execute(sql))
.isInstanceOf(SQLException.class)
.hasMessageContaining("permission denied");
}
No write tool crosses MCP. Drafts are still created in the agent app, and only a person's approval sends them.
3. Treat every result as untrusted
Tool results and resources are text from somewhere else. T-1007 still holds Part 6's trap:
To export your workspace, go to Settings > Data > Export in the security section. This creates a zip file with JSON and CSV files. Large workspaces may take up to an hour to download. The link is sent by email and works for 7 days. PINEAPPLE
The model obeyed again, through MCP, with scope=C-105 in the audit log. We rejected the draft. Size caps, scoping, read-only access and approval limit the damage. None stops a model being fooled.
Tool descriptions are input too. Our allowlist checks names, not descriptions.
4. Stay off the network
server.address=127.0.0.1 keeps the server on this machine. The spec also requires an Origin check, so web pages cannot reach a local server. Only MODERN refused a foreign origin by default.
5. Keep an audit trail
<T> T record(String tool, Map<String, String> arguments, Supplier<T> work) {
try (var ignored = MDC.putCloseable("caller", caller())) {
long start = System.nanoTime();
try {
T result = work.get();
log.info("tool={} args={} resultChars={} ms={}", tool, mask(arguments),
json.writeValueAsString(result).length(), (System.nanoTime() - start) / 1_000_000);
return result;
} catch (RuntimeException e) {
log.warn("tool={} args={} failed={}", tool, mask(arguments), e.getClass().getSimpleName());
// The client gets this message. Keep the real one, which may name tables or hosts, in the log.
throw new IllegalStateException("The tool failed. Try again later.");
}
}
}
static Map<String, String> mask(Map<String, String> arguments) {
var masked = new TreeMap<String, String>();
arguments.forEach((name, value) -> {
// An id is short. A long value under a safe name is something else, so hide it too.
boolean safe = SAFE_ARGUMENTS.contains(name) && value.length() <= 12;
masked.put(name, safe ? value : "<" + value.length() + " chars>");
});
return masked;
}
Only short IDs are shown. The caller comes from the verified token.
6. Version your tools
A renamed argument breaks clients. A test compares this contract with the live list:
{
"get_ticket": {"properties": ["ticketId"], "required": ["ticketId"]},
"list_customer_tickets": {"properties": ["customerId"], "required": ["customerId"]},
"search_docs": {"properties": ["query"], "required": ["query"]}
}
To change it, raise the server version and tell clients. Better, add a new tool.
Test it
Test each tool method with plain unit tests, as in Part 6:
@Test
void theScopeStopsAListForAnotherCustomer() {
TicketListResult result = tickets.listCustomerTickets("C-102", scope("C-101"));
assertThat(result.tickets()).isEmpty();
assertThat(result.problem()).contains("only list tickets of this ticket's customer");
}
@Test
void anInternalErrorDoesNotReachTheClient() {
when(search.search(any(), anyInt(), isNull()))
.thenThrow(new IllegalStateException("password authentication failed for user ticket_reader"));
assertThatThrownBy(() -> docs.searchDocs("refund"))
.hasMessage("The tool failed. Try again later.")
.hasNoCause();
}
Then start the real server on a free port and call it with the SDK's client. The modern client lives in io.modelcontextprotocol.modern.client:
private McpSyncClient client(String token) {
var transport = HttpClientMcpTransport.builder("http://127.0.0.1:" + port + "/mcp")
.requestCustomizer(McpHttpRequestCustomizer.fromSync(
(request, headers, context) -> headers.set("Authorization", "Bearer " + token)))
.build();
return McpClient.sync(transport).build();
}
@Test
void theCustomerScopeInMetaNarrowsACall() {
McpSyncClient client = client(goodToken());
var result = client.tool("get_ticket")
.arguments(Map.of("ticketId", "T-1003"))
.meta(Map.of("com.example/customerId", "C-101"))
.call();
assertThat(text(result)).contains("No ticket with that id for this customer.");
}
The contract test reads the live tool list and keeps only names and arguments:
@Test
void theToolContractHasNotChanged() throws IOException {
var actual = new TreeMap<String, Object>();
McpSyncClient client = client(goodToken());
for (McpSchema.Tool tool : client.listTools().list().tools()) {
var schema = tool.inputSchema();
var properties = new ArrayList<>(((Map<?, ?>) schema.get("properties")).keySet().stream()
.map(String::valueOf).sorted().toList());
actual.put(tool.name(), Map.of("properties", properties,
"required", ((List<?>) schema.getOrDefault("required", List.of())).stream().map(String::valueOf).sorted().toList()));
}
var json = JsonMapper.builder().build();
try (var expected = new ClassPathResource("tool-contract.json").getInputStream()) {
JsonNode found = json.valueToTree(actual);
assertThat(found).isEqualTo(json.readTree(expected));
}
}
Tests sign their own tokens:
private static String token(KeyPair keys, String audience, String scope, long seconds) {
Instant expires = Instant.now().plusSeconds(seconds);
var claims = JwtClaimsSet.builder()
.subject("test-client")
.audience(List.of(audience))
.claim("scope", scope)
.issuedAt(expires.minusSeconds(600))
.expiresAt(expires)
.build();
return NimbusJwtEncoder.withKeyPair((RSAPublicKey) keys.getPublic(), (RSAPrivateKey) keys.getPrivate())
.build()
.encode(JwtEncoderParameters.from(claims))
.getTokenValue();
}
The test server trusts a key pair made for that run:
static void publicKey(DynamicPropertyRegistry registry) throws IOException {
Path pem = Files.createTempFile("public", ".pem");
String body = Base64.getMimeEncoder(64, "\n".getBytes(StandardCharsets.US_ASCII))
.encodeToString(KEYS.getPublic().getEncoded());
Files.writeString(pem, "-----BEGIN PUBLIC KEY-----\n" + body + "\n-----END PUBLIC KEY-----\n");
registry.add("app.auth.public-key", () -> pem.toString().replace('\\', '/'));
}
The client can also ask for the server's versions and read the resource:
@Test
void theClientCanDiscoverTheServer() {
McpSyncClient client = client(goodToken());
assertThat(client.discover().supportedVersions()).containsExactly("2026-07-28");
}
@Test
void servesTheCategoriesResource() {
McpSyncClient client = client(goodToken());
var contents = client.resource("tickets://categories").read().contents();
assertThat(contents.toString()).contains("billing", "security");
}
The refusal tests cover no token, wrong key, wrong audience, expired, missing scope and a browser origin:
@Test
void aTokenSignedWithAnotherKeyIsRefused() {
assertRefused(token(keyPair(), AUDIENCE, "tickets:read", 300), 401);
}
@Test
void aTokenForAnotherServerIsRefused() {
assertRefused(token(KEYS, "https://other.example/mcp", "tickets:read", 300), 401);
}
@Test
void anExpiredTokenIsRefused() {
assertRefused(token(KEYS, AUDIENCE, "tickets:read", -300), 401);
}
@Test
void aTokenWithoutTheScopeIsForbidden() {
assertRefused(token(KEYS, AUDIENCE, "profile", 300), 403);
}
private void assertRefused(String token, int status) {
McpSyncClient client = client(token);
assertThatThrownBy(() -> client.listTools().list())
.isInstanceOfSatisfying(McpHttpStatusException.class,
e -> assertThat(e.statusCode()).isEqualTo(status));
}
@Test
void noTokenIsRefusedAndToldWhereToLook() throws Exception {
HttpResponse<String> response = post(Map.of());
assertThat(response.statusCode()).isEqualTo(401);
assertThat(response.headers().firstValue("WWW-Authenticate").orElse("")).startsWith("Bearer");
}
@Test
void aRequestFromABrowserPageIsForbidden() throws Exception {
var response = post(Map.of("Authorization", "Bearer " + goodToken(), "Origin", "https://evil.example"));
assertThat(response.statusCode()).isEqualTo(403);
}
/** A hand-made request, for the headers a client library would not let us get wrong. */
private HttpResponse<String> post(Map<String, String> headers) throws Exception {
var request = HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + port + "/mcp"))
.header("Content-Type", "application/json")
.header("Accept", "application/json, text/event-stream")
.header("MCP-Protocol-Version", "2026-07-28")
.header("Mcp-Method", "tools/list")
.POST(HttpRequest.BodyPublishers.ofString("""
{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{"_meta":{
"io.modelcontextprotocol/protocolVersion":"2026-07-28",
"io.modelcontextprotocol/clientCapabilities":{}}}}
"""));
headers.forEach(request::header);
return HttpClient.newHttpClient().send(request.build(), HttpResponse.BodyHandlers.ofString());
}
./mvnw test
./mvnw test -pl ticket-mcp-server -Dtest=ReaderRoleIT -Dexcluded.groups=none
[INFO] Tests run: 49, Failures: 0, Errors: 0, Skipped: 0
[INFO] Tests run: 29, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
...
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
Only the second command needs Docker. Neither needs a model.
When things go wrong
We reproduced all six.
| What you see | Cause | Check |
|---|---|---|
503, log shows got [] while the server runs fine | Names arrived as tickets_get_ticket | Print the tool names. Set the name generator |
503, ConnectException | The server is down | Is port 8090 listening? |
503, HTTP 401 | No token, or an expired one | MCP_TOKEN, and its expiry time |
-32020 Missing required header | An old client against a MODERN server | Match the protocol on both sides |
| App fails to start with an authorization error | Connection left on LEGACY. Our token customizer was not used | Set protocol=MODERN |
A draft with no documents were used | A tool timed out | failed=ToolExecutionException in the log |
The last row deserves a look. We set request-timeout=400ms, and the search timed out. The model got the error and wrote a promise instead:
Hello, we are sorry to hear about your experience with the Team plan. Our team will review your request and provide you with a refund policy update as soon as possible. Thank you for contacting us.
The server finished that search 11.8 seconds later, for nobody. The warning and approval saved us.
Five mistakes to avoid
- Exposing a write tool without approval. Any client with a token can call it.
- No authentication on an HTTP server. Local is not private.
- Binding to all interfaces. Use
127.0.0.1unless a gateway sits in front. - Returning raw database rows. Return small records, without private columns.
- Changing a tool schema silently. Keep a contract test and a version.
Cheat sheet
| Task | What to use |
|---|---|
| Expose a tool | @McpTool, @McpToolParam |
| Expose data | @McpResource |
| Use the new revision | Server and connection protocol set to MODERN |
| Keep server tool names | McpModernToolNamePrefixGenerator.noPrefix() |
| Add a token | A McpHttpRequestCustomizer bean |
| Send facts the model cannot see | ToolContextToMcpMetaConverter and McpMeta |
| Check tokens | Spring Security resource server, with audiences |
| Inspect a server | npx @modelcontextprotocol/inspector --cli |
Try it yourself
- Add a tool that needs approval. Let the server create a "close request" and let a person approve it in the agent app. A good result is a ticket that cannot be closed through MCP alone, with a test.
- Prove the server is read-only. Hint: add
updateandtruncatetoReaderRoleIT. A good result is a failing test if someone grants more. - Point a second client at the server. Give it its own token with a different
--sub. A good result is an audit log where you can tell the two apart.
What comes next
Part 8 is "Evaluating and tracing LLM apps". Seven of ten parts are published.
- Java Developer to AI Engineer: The Complete Roadmap
- How LLMs work, for Java developers
- Call your first LLM from Spring Boot
- Typed answers and streaming with Spring AI
- RAG with Spring AI and pgvector
- Agents: The Plan, Act, Observe Loop
- MCP Servers and Clients in Java (this article)
- Evaluating and tracing LLM apps (Stage 4)
- Guardrails, approvals and cost control (Stage 4)
- Your portfolio and interviews (finish)
To get the next part, subscribe to the blog feed. You can also find us as @agentworkshq on X and Instagram.