Skip to content

Commit 03eec58

Browse files
feat(mcp): note when a test key finds nothing
1 parent 8d9ac4d commit 03eec58

6 files changed

Lines changed: 169 additions & 12 deletions

File tree

‎js/packages/ng-postcode-mcp/src/contract.generated.json‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -317,6 +317,19 @@
317317
"default": null,
318318
"description": "Level 5, unstructured.",
319319
"title": "Point Geometry"
320+
},
321+
"note": {
322+
"anyOf": [
323+
{
324+
"type": "string"
325+
},
326+
{
327+
"type": "null"
328+
}
329+
],
330+
"default": null,
331+
"description": "Why the answer may be incomplete, such as a test key.",
332+
"title": "Note"
320333
}
321334
},
322335
"required": [
@@ -501,6 +514,19 @@
501514
"default": null,
502515
"description": "Level 5, unstructured.",
503516
"title": "Point Geometry"
517+
},
518+
"note": {
519+
"anyOf": [
520+
{
521+
"type": "string"
522+
},
523+
{
524+
"type": "null"
525+
}
526+
],
527+
"default": null,
528+
"description": "Why the answer may be incomplete, such as a test key.",
529+
"title": "Note"
504530
}
505531
},
506532
"required": [
@@ -837,6 +863,19 @@
837863
"default": null,
838864
"description": "How deep the match goes, e.g. unit.",
839865
"title": "Depth"
866+
},
867+
"note": {
868+
"anyOf": [
869+
{
870+
"type": "string"
871+
},
872+
{
873+
"type": "null"
874+
}
875+
],
876+
"default": null,
877+
"description": "Why the answer may be incomplete, such as a test key.",
878+
"title": "Note"
840879
}
841880
},
842881
"required": [

‎js/packages/ng-postcode-mcp/src/server.ts‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -82,14 +82,23 @@ export function createServer(settings: Settings): McpServer {
8282
);
8383
};
8484

85+
// A test key that finds nothing says so: NIPOST may hold the building.
86+
const testKey = /^nipost_(pk_)?test_/.test(settings.apiKey ?? "");
87+
const noted = <T extends object>(answer: T, missing: boolean) => ({
88+
...answer,
89+
note: missing && testKey ? "Asked with a test key, which may not see assigned codes." : null,
90+
});
91+
8592
const maxPaidCalls = settings.maxPaidCalls ?? 25;
8693
let paid = 0;
8794

8895
const handlers: Record<string, Handler> = {
8996
validate_postcode: ({ postcode }) => validation(String(postcode)),
9097

91-
lookup_postcode: async ({ postcode }) =>
92-
unwrap(await api().send(lookup(checked(String(postcode)), 1))),
98+
lookup_postcode: async ({ postcode }) => {
99+
const found = unwrap(await api().send(lookup(checked(String(postcode)), 1)));
100+
return noted(found, !found.valid);
101+
},
93102

94103
lookup_postcode_details: async ({ postcode, level = 2 }) => {
95104
if (Number(level) > settings.maxLevel) {
@@ -107,7 +116,8 @@ export function createServer(settings: Settings): McpServer {
107116
paid += 1;
108117
const result = await client.send(lookup(code, Number(level)));
109118
if (!reachedBilling(result)) paid -= 1;
110-
return unwrap(result);
119+
const found = unwrap(result);
120+
return noted(found, !found.valid);
111121
},
112122

113123
autocomplete_postcode: async ({ partial }) => {
@@ -120,7 +130,7 @@ export function createServer(settings: Settings): McpServer {
120130
const at = { lat: Number(latitude), lng: Number(longitude) };
121131
const metres = max_distance_m == null ? undefined : Number(max_distance_m);
122132
const { coordinate: _, ...found } = unwrap(await api().send(reverse(at, metres)));
123-
return capped(found, settings.maxLevel);
133+
return noted(capped(found, settings.maxLevel), !found.found);
124134
},
125135
};
126136

‎js/packages/ng-postcode-mcp/test/server.test.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,29 @@ test("autocompletes, and withholds address fields under the level cap", async ()
161161
expect(outside.isError).toBe(true);
162162
});
163163

164+
test("a test key that finds nothing says so", async () => {
165+
const answer = (async (url: URL, init: RequestInit) => {
166+
const found = (init.headers as Record<string, string>)["X-API-Key"]?.endsWith("found");
167+
const data = url.pathname === "/v1/lookup" ? { postcode: "x", valid: found } : { found };
168+
return Response.json({ data });
169+
}) as typeof fetch;
170+
const note = async (name: string, args: Record<string, unknown>, apiKey: string) => {
171+
const result = await call(await connect({ apiKey, fetch: answer }), name, args);
172+
return (result.structuredContent as { note: string | null }).note;
173+
};
174+
const calls: Array<[string, Record<string, unknown>]> = [
175+
["lookup_postcode", { postcode: "EK-01-A03-FK-01" }],
176+
["find_postcode_at_location", { latitude: 7.62, longitude: 5.22 }],
177+
];
178+
for (const [name, args] of calls) {
179+
expect(await note(name, args, "nipost_pk_test_1")).toBe(
180+
"Asked with a test key, which may not see assigned codes.",
181+
);
182+
expect(await note(name, args, "nipost_pk_test_found")).toBeNull();
183+
expect(await note(name, args, "nipost_live_1")).toBeNull();
184+
}
185+
});
186+
164187
test("the reported version is the package version", () => {
165188
const manifest = new URL("../package.json", import.meta.url);
166189
expect(VERSION).toBe(JSON.parse(readFileSync(manifest, "utf8")).version);

‎mcp/src/ng_postcode_mcp/server.py‎

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,9 @@ class PostcodeDetails(FromLibrary):
237237
building_use_status: str | None = Field(description="Level 3 and up, e.g. residential.")
238238
other_building_info: Any = Field(default=None, description="Level 4 and up, unstructured.")
239239
point_geometry: Any = Field(default=None, description="Level 5, unstructured.")
240+
note: str | None = Field(
241+
default=None, description="Why the answer may be incomplete, such as a test key."
242+
)
240243

241244

242245
class Completion(FromLibrary):
@@ -273,6 +276,9 @@ class Location(FromLibrary):
273276
message: str | None
274277
radius_m: float | None = Field(description="The radius the API actually applied.")
275278
depth: str | None = Field(default=None, description="How deep the match goes, e.g. unit.")
279+
note: str | None = Field(
280+
default=None, description="Why the answer may be incomplete, such as a test key."
281+
)
276282

277283

278284
@dataclass(frozen=True, slots=True)
@@ -369,8 +375,9 @@ async def lookup_postcode(
369375
370376
For the address and building details, use lookup_postcode_details.
371377
"""
372-
result = await api(ctx).send(lookup(checked(postcode), level))
373-
return PostcodeDetails.model_validate(unwrap(result))
378+
client = api(ctx)
379+
result = await client.send(lookup(checked(postcode), level))
380+
return noted(PostcodeDetails.model_validate(unwrap(result)), client)
374381

375382
async def lookup_postcode_details(
376383
postcode: Annotated[
@@ -413,7 +420,7 @@ async def lookup_postcode_details(
413420
result = await client.send(lookup(code, level))
414421
if mine and not reached_billing(result):
415422
state.paid[0] -= 1
416-
return PostcodeDetails.model_validate(unwrap(result))
423+
return noted(PostcodeDetails.model_validate(unwrap(result)), client)
417424

418425
# Not offered at all under the default cap, so a model cannot spend by accident.
419426
if settings.max_level >= 2:
@@ -476,10 +483,10 @@ async def find_postcode_at_location(
476483
477484
Names and the house address are withheld unless NG_POSTCODE_MAX_LEVEL is 2 or more.
478485
"""
479-
result = await api(ctx).send(
480-
reverse(Coordinate(lat=latitude, lng=longitude), max_distance_m)
481-
)
482-
return capped(Location.model_validate(unwrap(result)), settings.max_level)
486+
client = api(ctx)
487+
result = await client.send(reverse(Coordinate(lat=latitude, lng=longitude), max_distance_m))
488+
found = capped(Location.model_validate(unwrap(result)), settings.max_level)
489+
return noted(found, client)
483490

484491
@server.tool(
485492
title="Resolve a Nigerian address to a postcode",
@@ -595,6 +602,17 @@ def geocoder_for(settings: Settings, http: httpx.AsyncClient | None) -> Nominati
595602
)
596603

597604

605+
Answer = TypeVar("Answer", PostcodeDetails, Location)
606+
607+
TEST_KEY = "Asked with a test key, which may not see assigned codes."
608+
609+
610+
def noted(answer: Answer, client: AsyncClient) -> Answer:
611+
"""The answer, with a note when a test key found nothing: NIPOST may hold the building."""
612+
missing = not (answer.valid if isinstance(answer, PostcodeDetails) else answer.found)
613+
return answer.model_copy(update={"note": TEST_KEY}) if missing and client.test_key else answer
614+
615+
598616
def capped(location: Location, max_level: int) -> Location:
599617
"""The location with only the unit's level 1 fields, unless the cap allows more. Any
600618
field the unit gains later is withheld until it is listed as level 1."""

‎mcp/tests/test_tools.py‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -304,7 +304,35 @@ async def test_rejects_out_of_range_arguments() -> None:
304304
def test_output_models_only_use_fields_the_library_has(
305305
model: type[BaseModel], source: type
306306
) -> None:
307-
assert set(model.model_fields) <= {field.name for field in dataclasses.fields(source)}
307+
# The note is the server's own.
308+
fields = set(model.model_fields) - {"note"}
309+
assert fields <= {field.name for field in dataclasses.fields(source)}
310+
311+
312+
@pytest.mark.anyio
313+
async def test_a_test_key_that_finds_nothing_says_so() -> None:
314+
def handle(request: httpx.Request) -> httpx.Response:
315+
found = request.headers["X-API-Key"].endswith("found")
316+
if request.url.path == "/v1/lookup":
317+
return httpx.Response(200, json={"data": {"postcode": "x", "valid": found}})
318+
return httpx.Response(200, json={"data": {"found": found}})
319+
320+
async def note(tool: str, arguments: dict[str, Any], key: str) -> Any:
321+
http = httpx.AsyncClient(transport=httpx.MockTransport(handle))
322+
async with Client(create_server(Settings(api_key=key), http=http)) as client:
323+
result = await client.call_tool(tool, arguments)
324+
assert result.structured_content is not None
325+
return result.structured_content["note"]
326+
327+
calls: list[tuple[str, dict[str, Any]]] = [
328+
("lookup_postcode", {"postcode": "EK-01-A03-FK-01"}),
329+
("find_postcode_at_location", {"latitude": 7.62, "longitude": 5.22}),
330+
]
331+
for tool, arguments in calls:
332+
said = await note(tool, arguments, "nipost_pk_test_1")
333+
assert said == "Asked with a test key, which may not see assigned codes."
334+
assert await note(tool, arguments, "nipost_pk_test_found") is None
335+
assert await note(tool, arguments, "nipost_live_1") is None
308336

309337

310338
def test_transport_settings() -> None:

‎spec/mcp.json‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -317,6 +317,19 @@
317317
"default": null,
318318
"description": "Level 5, unstructured.",
319319
"title": "Point Geometry"
320+
},
321+
"note": {
322+
"anyOf": [
323+
{
324+
"type": "string"
325+
},
326+
{
327+
"type": "null"
328+
}
329+
],
330+
"default": null,
331+
"description": "Why the answer may be incomplete, such as a test key.",
332+
"title": "Note"
320333
}
321334
},
322335
"required": [
@@ -501,6 +514,19 @@
501514
"default": null,
502515
"description": "Level 5, unstructured.",
503516
"title": "Point Geometry"
517+
},
518+
"note": {
519+
"anyOf": [
520+
{
521+
"type": "string"
522+
},
523+
{
524+
"type": "null"
525+
}
526+
],
527+
"default": null,
528+
"description": "Why the answer may be incomplete, such as a test key.",
529+
"title": "Note"
504530
}
505531
},
506532
"required": [
@@ -837,6 +863,19 @@
837863
"default": null,
838864
"description": "How deep the match goes, e.g. unit.",
839865
"title": "Depth"
866+
},
867+
"note": {
868+
"anyOf": [
869+
{
870+
"type": "string"
871+
},
872+
{
873+
"type": "null"
874+
}
875+
],
876+
"default": null,
877+
"description": "Why the answer may be incomplete, such as a test key.",
878+
"title": "Note"
840879
}
841880
},
842881
"required": [

0 commit comments

Comments
 (0)