World Bank Documents MCP Server
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
World Bank Documents MCP Server + Groq Agent
A local MCP server that exposes the public World Bank Documents & Reports API, plus a CLI agent that uses a free LLM (Groq or Google Gemini) to answer natural-language questions grounded in real World Bank publications.
The deliverable covers the full loop required by the task:
question -> LLM picks tools -> MCP server calls the World Bank API
-> results returned to the LLM -> cited final answerNo World Bank authentication, database, frontend, or deployment is involved.
Contents
Related MCP server: worldbank-mcp
What is included
Path | Purpose |
| FastMCP server with the four required tools, stdio transport |
| Async HTTP client, response normalisation, pagination, sorting, retries, filter fallbacks |
| Pydantic request models, annotated tool parameter types, date parsing, facet aliases |
| MCP stdio client, MCP-to-Groq schema conversion, bounded tool-calling loop, CLI |
|
|
| Offline unit tests plus opt-in live integration tests |
| Manual live smoke test of the MCP tools without an LLM key |
| Pinned dependency ranges |
| Environment variable template |
Architecture
+--------------------------------------+
| client/agent.py (CLI / REPL) |
| |
user question | 1. start server subprocess (stdio) |
------------> | 2. list_tools -> Groq functions |
| 3. chat.completions(tools=...) |
| 4. execute tool_calls via MCP |
| 5. feed results back, repeat |
+------------------+-------------------+
| MCP over stdio
v
+--------------------------------------+
| server/wb_docs_mcp.py (FastMCP) |
| search_documents |
| filter_documents |
| get_document |
| get_facets |
+------------------+-------------------+
| HTTPS / JSON
v
+--------------------------------------+
| server/world_bank_api.py |
| httpx, retries, normalisation |
+------------------+-------------------+
|
v
https://search.worldbank.org/api/v3/wdsThe client launches the server itself with
python -m server.wb_docs_mcp, so the server does not need to be started
manually for normal use. The server subprocess deliberately does not inherit
GROQ_API_KEY; only the client needs it.
Requirements
Python 3.12+
One free LLM API key:
Groq: https://console.groq.com/keys (default), or
Google Gemini: https://aistudio.google.com/apikey
Internet access to
search.worldbank.orgOptional: Node.js if you want to use the MCP Inspector
The project was developed and tested with:
Python 3.12
FastMCP 4.2
MCP Python SDK 2.3
Groq Python SDK 1.7
OpenAI Python SDK 2.54 (used for Gemini's OpenAI-compatible endpoint)
HTTPX 0.28
Pydantic 2.14
Setup
Windows (PowerShell)
cd world-bank-mcp
python -m venv .venv
.\.venv\Scripts\Activate.ps1
pip install -r requirements.txt
Copy-Item .env.example .envmacOS / Linux
cd world-bank-mcp
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
cp .env.example .envOpen .env and set the key for the provider you want to use.
Groq (default):
GROQ_API_KEY=gsk_your_key_hereGoogle Gemini:
LLM_PROVIDER=gemini
GEMINI_API_KEY=your_gemini_key_hereThen verify the setup in two steps.
Confirm the MCP server starts and advertises its tools. This does not call the LLM and does not need an API key:
python -m client.agent --list-toolsExpected tool names:
search_documents
filter_documents
get_document
get_facetsConfirm the LLM key and model work. This sends one tiny request to the configured provider and does not start the MCP server:
python -m client.agent --check-llmExpected output:
Provider: Gemini
Model: gemini-2.5-flash
Response: OK
LLM connection OK.Configuration
All settings are optional except the API key for your chosen provider.
Variable | Default | Description |
| auto |
|
| none | Free Groq key. Required for the Groq provider. |
|
| Groq model used for tool calling ( |
| none | Optional OpenAI-compatible endpoint for the Groq SDK path (for example Ollama at |
| none | Free Google AI Studio key. Required for the Gemini provider. |
|
| Gemini model used for tool calling (for example |
| Gemini OpenAI endpoint | Override only if you proxy Gemini yourself. |
|
| Maximum LLM/tool rounds before a forced final answer. Clamped to 1-20. |
|
| Sampling temperature. Low value keeps answers factual. |
|
| Maximum tokens in each model response. |
|
| Token budget for the whole conversation (estimated as characters / 4). Older tool results are trimmed before each request to stay under it. |
|
| A single tool result larger than this is compacted/truncated before being sent back to the model. |
|
| Document abstracts are truncated to this length in tool results sent to the model. |
.env is loaded from the project root by client/groq_client.py. Real
environment variables take precedence over .env values.
Staying within free-tier rate limits
Free Groq and Gemini tiers cap tokens per minute (the Groq free tier allows 8,000 TPM per model). The client is built to stay inside that budget:
Document results are slimmed before being sent back to the model (short abstracts, no embedded facet blocks).
The whole conversation is kept under
MAX_CONTEXT_TOKENS; older tool results are replaced with a one-line note while the most recent result is preserved.If the provider still returns
413(request too large) or429(rate limit), the agent trims the context, waits for the provider'sRetry-Afterwhen given, and retries up to three times before reporting an informative error.
If you see repeated rate-limit retries, lower MAX_CONTEXT_TOKENS or ask for
fewer results (rows).
LLM choice
Default backend: Groq, model openai/gpt-oss-120b. Optional backend:
Google Gemini through its OpenAI-compatible endpoint.
Both providers are free to start and support native tool calling. The client
talks to each through its OpenAI-compatible chat.completions API, so the agent
loop, tool schemas, and message history are identical.
Why Groq by default
Free and fast. Groq's free tier is sufficient for this task and the low-latency inference keeps a multi-round tool loop responsive.
Native function/tool calling. The task requires a model that can emit structured tool calls;
openai/gpt-oss-120bsupports the OpenAI-compatibletoolsAPI used here.openai/gpt-oss-20bis a faster, lighter alternative andqwen/qwen3.8-27balso works.Good enough for tool selection. The four tools have explicit, LLM-oriented descriptions and narrow schemas, so a general-purpose open model reliably chooses between search, structured filtering, facet discovery, and document lookup.
Small and cheap to run repeatedly during development and evaluation.
Using Google Gemini instead
Gemini exposes an OpenAI-compatible endpoint at
https://generativelanguage.googleapis.com/v1beta/openai/. Add a free Google AI
Studio key and select the provider:
LLM_PROVIDER=gemini
GEMINI_API_KEY=your_gemini_key_here
GEMINI_MODEL=gemini-2.5-flashThe client detects the provider automatically when only GEMINI_API_KEY is set,
so LLM_PROVIDER is optional. Any Gemini model that supports function calling
can be used, for example gemini-2.5-flash, gemini-2.5-flash-lite,
gemini-3.6-flash, or the gemini-flash-latest alias.
Other OpenAI-compatible endpoints
The Groq SDK path accepts any OpenAI-compatible base URL. A fully offline setup can use Ollama with a tool-capable model:
LLM_PROVIDER=groq
GROQ_BASE_URL=http://localhost:11434/v1
GROQ_MODEL=qwen2.5:3b
# GROQ_API_KEY can stay empty for a local serverNo client code changes are required. If no usable key or base URL is configured, the client exits with a clear configuration error.
The exact model can be overridden per run:
python -m client.agent --model llama-3.3-70b-versatile "What is the newest report on Indonesia?"Running the agent
One-shot question
python -m client.agent "What World Bank reports exist on climate resilience in Kenya?"The final answer is printed to stdout. Diagnostics, such as tool progress
when --show-tools is used, go to stderr.
Interactive mode
python -m client.agent --interactiveWorld Bank Documents agent. Type a question, or 'exit' to quit.
Question> Find project documents about water and sanitation in Brazil.
...
Question> exitThe MCP subprocess and Groq client stay open between questions. Each question starts a fresh conversation, so answers are not contaminated by earlier turns.
Inspect tool calls
python -m client.agent --show-tools "What document types are most common?"Example stderr trace:
[tool] search_documents({"qterm": "document types", "rows": 5})
[tool] search_documents -> ok (7421 chars)Other CLI options
python -m client.agent --list-tools # print discovered schemas
python -m client.agent --check-llm # verify the provider key/model
python -m client.agent --show-tools "..." # trace tool calls
python -m client.agent --max-iterations 8 "..." # change the loop bound
python -m client.agent --model <model-id> "..." # override the provider modelRun the server directly
For MCP Inspector or another MCP client:
python -m server.wb_docs_mcpThe server speaks MCP over stdio. It is not an HTTP server, so running it in a terminal will simply wait for JSON-RPC messages on stdin.
With the MCP Inspector:
npx @modelcontextprotocol/inspector python -m server.wb_docs_mcpSmoke test without Groq
python scripts/smoke_test.pyThis starts the real stdio server and calls all four tools against the live World Bank API. It requires no LLM key.
MCP tools
All parameters are validated with Pydantic. Invalid values are rejected before an HTTP request is made, and the error message names the offending field.
search_documents
Full-text search with optional language filtering, pagination, and sorting.
Parameter | Type | Default | Notes |
| string, 1-300 chars | required | Keywords across titles, abstracts, countries, project names, report numbers |
| string or null |
| Exact language name, e.g. |
| integer 1-50 |
| Results per page |
| integer >= 0 |
| Zero-based offset; use |
|
|
|
|
Returns total, offset, rows, returned, has_more, next_offset, sort,
and a documents list.
filter_documents
Structured filtering by country, region, topic, document type, and/or date
range. At least one filter (or qterm) is required, so the tool never returns an
unbounded result set.
Parameter | Type | Default | Notes |
| string or null |
| Optional keywords combined with the filters |
| string or null |
| Exact country or regional grouping, e.g. |
| string or null |
| World Bank region, e.g. |
| string or null |
| Topic or sector, e.g. |
| string or null |
| Exact type, e.g. |
| date or null |
| Inclusive. |
| date or null |
| Inclusive. A bare year such as |
| integer 1-50 |
| Results per page |
| integer >= 0 |
| Pagination offset |
|
|
| Date sorting when requested |
Returns the same pagination/document structure as search_documents, plus:
filters: the exact World Bank API parameters that were used.notes: human-readable explanations when a fallback was applied.
Date order is validated locally: start_date > end_date is an error.
get_document
Retrieves full metadata for one document.
Parameter | Type | Notes |
| string | Numeric World Bank ID such as |
Returns the normalised summary fields plus a metadata dictionary with the
remaining API fields (authors, theme, sector, major document type, disclosure
date, volume, and so on). Unknown IDs produce an informative tool error rather
than an empty object.
get_facets
Discovers distinct values for a filter field.
Parameter | Type | Default | Notes |
| string | required |
|
| string or null |
| Optional keyword scope, e.g. |
| integer 0-1000 |
| Maximum values, sorted by document count. |
Returns field, api_field (the actual WDS facet used),
total_matching_documents, total_values, returned, has_more, and a
values list of {"value", "count"} objects.
The four tools are intentionally named and described for an LLM, not for a human API wrapper. Each docstring states when to use the tool, what every argument means, and what the result contains.
How the agent loop works
client/agent.py implements the required MCP client behaviour:
Start the MCP server as a subprocess.
open_mcp_session()usesmcp.client.stdio.stdio_clientwithsys.executable -m server.wb_docs_mcp, sets the project root onPYTHONPATH, and initialises aClientSession.Discover tools dynamically.
session.list_tools()is called at runtime; no tool names or schemas are hard-coded in the client.Convert MCP schemas to Groq functions. Each MCP tool becomes
{"type": "function", "function": {"name", "description", "parameters"}}.anyOf: [X, null]optional fields are flattened because small models handle the simpler schema more reliably.Send the conversation to the LLM provider (Groq or Gemini) with
tools=...andtool_choice="auto".Preserve assistant tool-call messages. The assistant message is appended with its
tool_callsarray exactly as returned, including each callid.Execute every requested tool through the MCP session. Arguments are parsed from the model's JSON string into a dict. Tool errors are converted to JSON and fed back to the model instead of crashing the loop.
Return each result by
tool_call_id. Every tool result is a{"role": "tool", "tool_call_id": ..., "content": ...}message. Thenamefield is intentionally omitted, matching the current Groq/OpenAI tool protocol.Repeat until the model returns a message with no tool calls, or the iteration limit is reached.
Bound the loop. After
AGENT_MAX_ITERATIONSrounds, one final completion is requested withtoolsdisabled and an explicit instruction to answer from the results already gathered. This prevents infinite tool loops.
Oversized tool results are compacted before being sent back: document abstracts
are truncated, embedded facet blocks are dropped, strings are shortened, and
lists are capped. The final serialised result is truncated to
MAX_TOOL_RESULT_CHARS while remaining valid JSON, and the whole conversation is
kept under MAX_CONTEXT_TOKENS by replacing older tool results with a short
note (see Staying within free-tier rate limits above).
The system prompt reinforces grounding: use tool results only, never invent
titles/IDs/URLs, use structured filters for structured questions, use
sort="newest" for "latest" questions, use facets before exact filtering, and
cite title, date, country, and URL.
Data handling and API fallbacks
The live WDS API has several quirks that the server handles so the LLM does not have to:
documentsis an object, not a list. It also contains afacetskey. The normaliser filters outfacetsbefore iterating.Modern topic fields are empty.
topic_exactoften returns zero results for current records.filter_documentstherefore retries in order withtopic_exact, then the legacyteratopic_exact, thensectr_exact, and reports the fallback innotes.Region names are not country names.
country="Sub-Saharan Africa"is expanded toadmreg_exact=Eastern and Southern Africa^Western and Central Africa. Other region-like country values are also detected and mapped.Document URLs use GUIDs, not IDs.
get_documentfirst looks up the numeric WDSid; if that finds nothing, it retries withguid. Both a tool result ID and the number in a document URL work.ISO dates are required by the API. Compact dates such as
20240101can produce an HTTP 500. The schema acceptsYYYY-MM-DD, common slash/dash variants, and bare years, then sends ISO dates to WDS.Sorting needs explicit parameters. WDS honours
srt=docdt&order=desc|ascfor date sorting. Without a query, the API already tends to return the newest records first, but the tool makes the intent explicit viasort.
Normalised document fields include: id, title, date, country, region,
document_type, language, project, report_number, a short abstract,
url, and pdf_url.
Error handling and limits
Situation | Behaviour |
Invalid tool arguments | Pydantic validation runs before the HTTP call; the MCP tool raises a |
Malformed JSON from the model | The loop reports the parse error back to the model as a tool result, so it can retry with valid arguments. |
World Bank 4xx | Returned immediately as an informative error (status, short response detail, URL). |
World Bank 429 / 5xx | Retried up to 3 times with exponential backoff ( |
Timeout / network failure | Clear "timed out" or "could not reach" message; retried with the same backoff. |
Non-JSON response | Reported as an unexpected API response instead of a JSON decode traceback. |
Zero results | Not an error. The agent is instructed to broaden keywords or relax filters and to say when nothing matches. |
Unknown document ID |
|
Missing provider API key | The client prints a configuration error and exits with status 2. |
Provider 401/403 | Explains that the credentials were rejected and points to |
Provider 413 | Explains that the request exceeded the per-minute budget and that older tool results are trimmed automatically. |
Provider 429 | Explains the rate limit, trims the context, and retries after the provider's |
Tool-call limit reached | One final answer is requested without tools; the run fails only if that answer is empty. |
Input bounds: rows is 1-50, offset is capped at 100,000, qterm is at most
300 characters, and facet limit is 0-1000. These limits keep individual tool
results small enough for a small-context, small-model loop.
Example questions and outputs
Data note: the tool results below were captured from the live World Bank API. The answers are written in the agent's required style; with a Groq or Gemini key in
.envthe same questions produce the same grounding data with model-written prose. The Other suggested questions verified live section below includes runs captured verbatim with Groqopenai/gpt-oss-120b.
1. Climate resilience reports in Kenya
Question
python -m client.agent "What World Bank reports exist on climate resilience in Kenya?"Tool call
{
"name": "search_documents",
"arguments": {"qterm": "climate resilience Kenya", "rows": 5}
}Tool result (summary)
total: 962
returned: 5
documents:
33295056 | 2021-07-01 | Resettlement Plan | Kenya
... | 2015-07-29 | Auditing Document | Kenya
... | 2021-02-01 | Resettlement Plan | Kenya
... | 2020-12-15 | Project Paper | Kenya,World
... | 2015-12-02 | Implementation Status and Results Report | KenyaAnswer
The World Bank API returns 962 documents for climate resilience work in Kenya. The most relevant results are:
Kenya - Coastal Region Water Security and Climate Resilience Project: Resettlement Plan (Vol. 4 of 4): Resettlement Action Plan 2 for Mwache Multipurpose Dam Project (Resettlement Plan, July 2021). https://documents.worldbank.org/curated/en/633061627382758577
Kenya - Water Security and Climate Resilience Project: audited financial statement - year ending June 30, 2015 (Auditing Document, July 2015). https://documents.worldbank.org/curated/en/948341438174804516
Kenya - Coastal Region Water Security and Climate Resilience Project: Resettlement Plan (Vol. 3 of 4) (Resettlement Plan, February 2021). https://documents.worldbank.org/curated/en/533081616664378297
Disclosable Restructuring Paper - Kenya Water Security and Climate Resilience Project - P117635 (Project Paper, December 2020). https://documents.worldbank.org/curated/en/595061608021784702
These are the top results among 962 matches; more pages are available with rows
and next_offset.
2. Education financing in Sub-Saharan Africa, 2019-2022
Question
python -m client.agent "Find documents about education financing in Sub-Saharan Africa published between 2019 and 2022."Tool call
{
"name": "filter_documents",
"arguments": {
"country": "Sub-Saharan Africa",
"topic": "Education",
"qterm": "financing",
"start_date": "2019",
"end_date": "2022",
"rows": 5
}
}Tool result (summary)
total: 4148
filters: {
"qterm": "financing",
"admreg_exact": "Eastern and Southern Africa^Western and Central Africa",
"strdate": "2019-01-01",
"enddate": "2022-12-31",
"teratopic_exact": "Education"
}
notes:
- Country 'Sub-Saharan Africa' was interpreted as a World Bank region.
- topic_exact returned no matches; retried with the legacy topic field (teratopic_exact).Answer
There are 4,148 documents matching education financing in Sub-Saharan Africa between 2019 and 2022. The top results include:
Ethiopia - Education Results Based Financing Project (Implementation Completion and Results Report, 27 December 2019). https://documents.worldbank.org/curated/en/278011579096308073
Mozambique - Can Results-Based Financing Ensure that Books Reach Students in Time for the Start of the School Year? (Brief, April 2021). https://documents.worldbank.org/curated/en/964841619414972572
South Africa - Results-Based Financing and the Book Supply Chain (Brief, December 2019). https://documents.worldbank.org/curated/en/330561577181324343
Two Implementation Status and Results Reports for the Ethiopia Education Results Based Financing Project (P163608), both from 2019. https://documents.worldbank.org/curated/en/426241554676766545 https://documents.worldbank.org/curated/en/874871561749593107
"Sub-Saharan Africa" was mapped to the World Bank's Eastern and Southern Africa
and Western and Central Africa regions, and the legacy topic field was used
because the current topic_exact field returned no matches for modern records.
3. Most frequent document types
Question
python -m client.agent "What document types does the World Bank publish most frequently?"Tool call
{
"name": "get_facets",
"arguments": {"field": "document_type", "limit": 5}
}Tool result (summary)
total_matching_documents: 623114
total_values: 100
values:
Procurement Plan 144,407
Implementation Status and Results Report 59,904
Auditing Document 30,490
Working Paper 27,069
Brief 24,818Answer
Across 623,114 documents in the World Bank Documents & Reports API, the most frequently published document types are:
Rank | Document type | Documents |
1 | Procurement Plan | 144,407 |
2 | Implementation Status and Results Report | 59,904 |
3 | Auditing Document | 30,490 |
4 | Working Paper | 27,069 |
5 | Brief | 24,818 |
Together, Procurement Plans and Implementation Status and Results Reports make
up roughly one third of the collection. These counts come from the API's
document_type facet, which reports 100 distinct values in total.
Other suggested questions verified live
Question | Tool path | Verified result |
Find the most recent economic sector work on Indonesia. |
| 2,483 matches; newest is Indonesia - Country Private Sector Diagnostic (5 October 2026), https://documents.worldbank.org/curated/en/099753310052628862 |
List all languages the World Bank publishes documents in. |
| English 578,402; French 16,611; Spanish 10,408; Arabic 3,025; Portuguese 2,913; ... (100 distinct values) |
Find project documents related to water and sanitation in Brazil. |
| 3,909 matches; top result All Drops in the Bucket for Universalization: Public Expenditure Review of Water and Sanitation in Brazil (March 2022), https://documents.worldbank.org/curated/en/363231625052894706 |
Verbatim runs with openai/gpt-oss-120b
Two complete agent runs captured against the live Groq API and the live World Bank API (tool calls shown, then the model's answer).
Q: What languages does the World Bank publish in? List the top few.
Tool path: get_facets(field="language", limit=5).
The World Bank publishes its documents primarily in the following languages (top 5 by document count):
| Rank | Language | Approx. number of documents |
|------|------------|----------------------------|
| 1 | English | 578,410 |
| 2 | French | 16,611 |
| 3 | Spanish | 10,408 |
| 4 | Arabic | 3,025 |
| 5 | Portuguese | 2,913 |
Source: World Bank Documents & Reports API facet query for "language" (top 5 values) - total matching documents = 623,122.Q: Show the most recent World Bank reports on education in Sub-Saharan Africa.
Tool path: filter_documents(country="Sub-Saharan Africa", topic="Education", document_type="Report", sort="newest") (with a search fallback).
Most recent World Bank Reports on Education in Sub-Saharan Africa (newest first)
1. Final Evaluation of the Transparency of the Mauritanian Education Budget (TOME) Project - August 2022 - Mauritania (Western and Central Africa) - https://documents.worldbank.org/curated/en/352401647610255802
2. Understanding the Socio-Economic Conditions of Urban Refugees in Kenya (2020-2021 Urban Socio-economic Survey) - May 2022 - Kenya (Eastern and Southern Africa) - https://documents.worldbank.org/curated/en/184981636366231985
3. Final Evaluation of the Transparency of the Mauritanian Education Budget (TOME) Project (French version) - February 2022 - Mauritania (Western and Central Africa) - https://documents.worldbank.org/curated/en/254021647610543043
4. l'Emploi des Jeunes dans les Chaines de Valeur au Burkina Faso - November 2021 - Burkina Faso (Western and Central Africa) - https://documents.worldbank.org/curated/en/616721636445034078
5. Cote d'Ivoire - Sustaining High, Inclusive, and Resilient Growth Post COVID-19 - October 2021 - Cote d'Ivoire (Western and Central Africa) - https://documents.worldbank.org/curated/en/877591635251242567
... (10 shown in total)
Summary: the query returned 208 matching reports; the list shows the 10 most recent, sorted by newest publication date. More results are available (the API indicates additional pages).Outputs vary slightly between runs (temperature 0.1) and may include a short rate-limit retry notice on the free tier, as described in Staying within free-tier rate limits.
Tests
The offline suite mocks HTTP, the MCP session, and the LLM, so it runs without a network connection or API key:
python -m pytestResult at delivery time:
66 passed, 2 skippedThe two skipped tests are the live integration tests. They exercise the real World Bank API and a real stdio server subprocess:
# Windows PowerShell
$env:RUN_WB_INTEGRATION = "1"
python -m pytest -m integration# macOS / Linux
RUN_WB_INTEGRATION=1 python -m pytest -m integrationResult at delivery time:
2 passedCoverage includes:
tests/test_api.py- URL parameter construction, normalisation, facets, sorting, retries, timeouts, error messages, GUID fallback, topic fallback.tests/test_tools.py- in-memory FastMCPClientcalls, Pydantic validation, pagination metadata, facet aliases, document lookup errors.tests/test_agent.py- MCP-to-Groq schema conversion,anyOfflattening,additionalPropertiesremoval, argument parsing, multi-round tool loops, assistanttool_callsretention,tool_call_idcorrelation, tool errors, truncation, iteration bounds, token-budget trimming, and 413/429 retries.tests/test_llm_config.py- provider auto-detection, explicit provider selection, model defaults/overrides, and configuration errors for Groq and Gemini.tests/test_integration.py- live WDS API and real stdio server startup (opt-in).
A separate end-to-end check was also run with the real Groq SDK, the real stdio
MCP server, and the live World Bank API, using a local OpenAI-compatible test
double in place of the remote model. It confirmed that the tool result is
returned under the correct tool_call_id and that the second LLM call receives
the full assistant-plus-tool message history. The same path was then run against
the live Groq API with openai/gpt-oss-120b; the rate-limit handling above was
added in response to the free tier's 8,000 TPM cap.
Project layout
world-bank-mcp/
|-- client/
| |-- __init__.py
| |-- agent.py # stdio session, schema conversion, agent loop, CLI
| `-- groq_client.py # .env loading, provider setup, env defaults
|-- server/
| |-- __init__.py
| |-- schemas.py # Pydantic models and annotated tool parameter types
| |-- wb_docs_mcp.py # FastMCP server and the four tools
| `-- world_bank_api.py # HTTP client, retries, normalisation, fallbacks
|-- scripts/
| `-- smoke_test.py # live tool smoke test without an LLM
|-- tests/
| |-- conftest.py
| |-- test_agent.py
| |-- test_api.py
| |-- test_integration.py
| |-- test_llm_config.py
| `-- test_tools.py
|-- .env.example
|-- .gitignore
|-- pytest.ini
|-- requirements.txt
`-- README.mdHow this was built
The work followed the order the task suggested: server first, then the agent, then hardening.
Server first, tested without an LLM. The four tools were written against the live World Bank API and exercised directly with
scripts/smoke_test.pyand the MCP Inspector, so the tool layer was correct before any model was involved.Descriptions written for the model, not the reader. Each docstring states when to use the tool, what every argument means, and what the result contains, because the LLM reads those descriptions to choose a tool.
The agent loop was built against a test double. A local OpenAI-compatible server stood in for the remote model, so the loop could be checked deterministically: MCP-to-function schema conversion, assistant
tool_callsretention,tool_call_idcorrelation, and the multi-round message history.API quirks were discovered empirically. Zero-result
topic_exactqueries, region names passed as countries, GUID-versus-ID lookups and the API's ISO-date requirement were all found by querying the live API, then handled in the server and reported in the tool result'snotesfield.Hardening came from a real failure. The first live Groq runs died with an opaque
ExceptionGroup; unwrapping it revealed a413 Request too largefrom the free tier's 8,000 TPM cap. That produced the token budget, the tool-result slimming, and the 413/429 retry path.Tests were written alongside the code. The offline suite mocks HTTP, the MCP session and the LLM, so it runs with no network and no API key; the live integration tests are opt-in via
RUN_WB_INTEGRATION=1.
Built with Python 3.12, FastMCP, the MCP Python SDK, the Groq Python SDK, HTTPX,
Pydantic and pytest. A slide deck summarising the project lives in
docs/presentation/.
Design notes and limitations
The MCP server is the unit of reuse. The client knows nothing about the World Bank API; it only knows MCP tools. Any MCP-compatible client can use the server.
Tool descriptions are part of the interface. Each docstring explains when to use the tool and what the output means, which matters more for a small model than implementation detail.
No caching. Every question reflects the live API. This keeps the demo honest but means repeated questions make repeated HTTP requests.
Relevance ranking is the API's. WDS relevance search can surface older documents first. The
sortparameter exists specifically so "latest" and "newest" questions can request date order instead.Facet values are API-capped. The live API currently exposes 100 distinct values per facet, so
get_facetsreportstotal_values: 100even when more languages or document types may exist in the underlying collection.Dates are document dates.
docdtis the disclosure/publication date used by WDS, not necessarily the date the underlying work was completed.Model variability.
openai/gpt-oss-120bis free but can occasionally choose a broad query or over-explore with extra tool calls. The system prompt, the bounded loop, the token budget, and the structured tool output reduce that risk; a different Groq model can be selected with--modelif desired.No streaming, persistence, or UI. These were explicitly out of scope for the task.
License
Released under the MIT License. See LICENSE.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Search, read and cite documents. Add, replace and delete files with write access. OAuth required.
Search and query government open-data portals (Socrata SODA API).
Search ReliefWeb humanitarian reports, disasters, jobs, training, and country profiles via MCP.
Search Visa Developer docs and retrieve OpenAPI specs for Visa product APIs to build integrations.
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceEnables discovery and retrieval of World Bank reports and publications through the Documents & Reports API. It supports full-text search, structured filtering by topic or country, and metadata extraction for research and data analysis.-
- AlicenseNot gradedqualityDmaintenanceProvides query capabilities for global economic and social development data from the World Bank Open Data API.95 npm8MIT
- AlicenseBqualityDmaintenanceEnables searching, retrieving, and exploring World Bank documents and reports through natural language queries with advanced filtering options.41MIT
- FlicenseNot gradedqualityDmaintenanceEnables searching and fetching World Bank procurement notices using the public API. Supports filtering by country, sector, and notice type, and retrieving full details by ID.-