legislation.gov.uk MCP Server
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@legislation.gov.uk MCP Server show me section 12 of the Human Rights Act 1998"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
legislation.gov.uk MCP Server
Model Context Protocol (MCP) server providing AI assistants with access to UK legislation from legislation.gov.uk.
Features
Tools
search_legislation - Search by keyword (
q), title, or metadata filters:type(single or multi-value, including aggregates likeprimary/secondary),year/startYear/endYear,subject,department,extent(E/W/S/NI), andlanguage(english/welsh). Order results withsort(relevance, published, title, type, subject, basic). Returns 20 results per page with pagination support (pageparameter,meta.morePagesflag).search_legislation_advanced (needs the Research API) - Advanced structured search over legislation XML via the Research API. Supports proximity queries, element-scoped matching (titles, chapters, paragraphs, footnotes), boolean logic, range queries, and counting. Takes a
querystring in the advanced query syntax (seeadvanced://query-syntax).count_legislation_advanced (needs the Research API) - Count documents or document features (paragraphs, schedules, footnotes, etc.) using the advanced query syntax, with optional grouping by department, subject, year, etc.
get_legislation - Retrieve full legislation documents. Default format is plain text; also supports XML (CLML), Akoma Ntoso, and HTML. Plain-text responses include an up-to-date callout listing any unapplied effects.
get_legislation_metadata - Get structured JSON metadata for a document or a specific fragment (e.g.
section/12,part/2/chapter/1). Returns status, extent, key dates, available versions, and unapplied effects. Supports point-in-time versions and Welsh-language metadata for bilingual legislation.get_legislation_fragment - Retrieve a specific fragment (section, part, etc.) of a legislation document. Default format is plain text.
get_legislation_table_of_contents - Retrieve the table of contents for a piece of legislation. Default format is structured JSON.
search_effects - Search legislative effects (amendments, repeals, insertions) by source (affecting) and/or target (affected) legislation. Filter by
appliedstatus to find unapplied amendments.search_legislation_semantic (needs the semantic search backend) - Semantic search across legislation using vector index (experimental)
search_legislation_sections_semantic (needs the semantic search backend) - Semantic search across individual sections (experimental)
get_resource - Fetch an MCP resource by URI. Intended for API-connected agents that support tool calls but cannot access MCP resources directly; not needed for local MCP clients.
Tools marked (needs ...) are registered only when their backend is configured — they are absent from the tool list otherwise, rather than being advertised and failing when called. An install with none of the optional backends offers the seven unmarked tools above; setting the relevant environment variables and restarting brings the others back. The server logs its Node.js version and which backends are active at startup:
[init] Node.js v24.22.2
[init] Semantic search backend: disabled (needs SEMANTIC_API_BASE_URL)
[init] Research API backend: https://research.legislation.gov.uk
[init] Duties backend: disabled (needs DUTIES_DB_CLUSTER_ARN + DUTIES_DB_SECRET_ARN)Powers and Duties
These three tools are registered only when the duties Postgres backend is configured (see Powers and Duties Database below).
search_powers_and_duties - Search The National Archives' powers-and-duties research dataset. Each row identifies a power or duty granted to or imposed on an actor by a specific provision of UK legislation, with the action expressed in plain English. Free-text
querysupports implicit AND,"quoted phrases",ORbetween terms, and-negation; combine with filters forenactment_type, year range,actor,modality(duty/power),priority(primary/secondary), andinference(explicit/implicit).count_powers_and_duties - Count rows in the dataset, optionally grouped by one dimension (
enactment_type,enactment_year,actor,modality,priority,inference, orenactment_uri). Grouped results are top-N by count, with agroupsTruncatedflag.get_powers_and_duties - Return all powers and duties for a single Act, SI, or Regulation, in best-effort provision order. Paginated, with an optional duty-vs-power
modalityBreakdown.
The dataset is a research extract: each row carries the date it was captured (extractedAsOf) and reflects the legislation as it stood then, not necessarily current law.
Resources
The server provides documentation resources grouped by namespace:
guide://- Getting started and troubleshooting (getting-started,troubleshooting)types://- Legislation type codes (guide,data)atom://feed-guide- Search result (Atom feed) parsing guideclml://- CLML XML reference (schema-guide,metadata/extent)advanced://query-syntax- Query syntax forsearch_legislation_advanced/count_legislation_advancedtext://format-guide- Plain-text output format referencejson://- Response shape references for the JSON-returning tools (search-response,advanced-search-response,metadata-response,table-of-contents-response,semantic-search-response,semantic-section-response)cookbook://- Task-oriented recipes:index(list of all recipes),check-extent,check-outstanding-effects,point-in-time-version,search-effects,find-recent-si-by-subject,semantic-search-workflowyears://regnal- Regnal-year identifiers for pre-1963 Acts
Related MCP server: gb-eli-mcp
Installation
npm install
npm run buildNote: The build process generates a resource manifest from files in src/resources/. This manifest is required at runtime and is created automatically during the build.
Configuration
Environment Variables
The server can be configured using environment variables:
Research API (Optional)
search_legislation_advanced and count_legislation_advanced are registered only when both RESEARCH_API_USERNAME and RESEARCH_API_PASSWORD are set; without them the tools are not offered to the client (every request would be a 401). The standard legislation.gov.uk tools work independently of Research API configuration.
RESEARCH_API_BASE_URL- Base URL for the Research APIDefault:
https://research.legislation.gov.uk
RESEARCH_API_USERNAME- Basic-auth usernameRESEARCH_API_PASSWORD- Basic-auth password
Semantic Search (Optional)
SEMANTIC_API_BASE_URL- Base URL for the semantic search APIDefault:
http://localhost:8000Example:
https://semantic-api.example.com
SEMANTIC_API_KEY- API key for semantic search authenticationDefault: None
Example:
sk-xxx...
search_legislation_semantic and search_legislation_sections_semantic are registered only when SEMANTIC_API_BASE_URL is set; without it the tools are not offered to the client. Set it explicitly even when the backend is at the default address — the default applies to the client, not to whether the tools are registered. The standard legislation.gov.uk tools work independently of semantic search configuration.
Upgrading:
SEMANTIC_API_BASE_URLused to be optional — the client fell back tohttp://localhost:8000, so a server with the variable unset still offered the semantic tools and reached a Lex instance running at that address. It now gates registration, so an install that relied on the implicit default loses the semantic tools with no error beyond one[init]line on stderr. If that describes yours, setSEMANTIC_API_BASE_URL=http://localhost:8000explicitly and restart.
Powers and Duties Database (Optional)
The powers-and-duties tools are backed by an Aurora Serverless v2 Postgres cluster reached over the RDS Data API. Like the Research API and semantic tools, they are registered only when their backend is configured. If DUTIES_DB_CLUSTER_ARN or DUTIES_DB_SECRET_ARN is missing, the server logs [init] Duties backend: disabled (needs DUTIES_DB_CLUSTER_ARN + DUTIES_DB_SECRET_ARN) at startup and search_powers_and_duties, count_powers_and_duties, and get_powers_and_duties are absent from the tool list. All other tools are unaffected.
DUTIES_DB_CLUSTER_ARN- ARN of the Aurora cluster (required)DUTIES_DB_SECRET_ARN- ARN of the Secrets Manager secret holding the database credentials (required)DUTIES_DB_NAME- Database nameDefault:
duties
AWS_REGION- AWS region for the Data API clientDefault:
eu-west-2
Standard AWS credentials must also be available to the process (via the usual credential chain — environment variables, shared config, or an instance/task role).
In production DUTIES_DB_SECRET_ARN is the read-only role's secret (mcp_ro), not the cluster's master credentials — the App Runner instance role can read that one secret and holds a single Data API action, rds-data:ExecuteStatement. The master secret is operator-only, for the schema, ingest and role-provisioning scripts. Locally you can point at either; the read-only one is the closer mirror of production. See infra/docs/adr/2026-05-29-postgres-migration-plan.md.
The mcp_ro role is created by scripts/apply-readonly-role.js, not by deploying — a freshly provisioned cluster needs it run once, and again after any rotation of the read-only secret or any change to the set of tables the role may read (READABLE_TABLES in that script). Ordinary schema changes and re-ingests do not need it: the grants are table-scoped and the duties ingest TRUNCATEs rather than replacing the table. The script finishes by authenticating as mcp_ro and reading duties for real, so a password mismatch between the secret and the role fails there rather than after deploy. Before touching the database at all, it refuses a read-only secret whose username is the master, or anything other than the configured read-only role (mcp_ro, overridable with DUTIES_DB_RO_USERNAME) — so pointing DUTIES_DB_RO_SECRET_ARN at the wrong secret stops the run instead of resetting some other role's password.
Transport Mode
MCP_TRANSPORT- Communication transport (stdio or http)Default:
stdioOptions:
stdio,http
When using HTTP transport:
PORT- HTTP server portDefault:
3000
MCP_SERVER_KEY- Optional bearer token. If set, clients must sendAuthorization: Bearer <key>on the/mcpendpoint. If unset, authentication is disabled.
Example Configurations
Local Development (stdio):
npm startLocal Development with Semantic Search:
SEMANTIC_API_BASE_URL=http://localhost:8000 npm startHTTP Transport (for remote access):
MCP_TRANSPORT=http PORT=3000 npm startDocker:
docker build -t legislation-mcp .
docker run -e MCP_TRANSPORT=http -p 3000:3000 legislation-mcpTo use semantic search with Docker, pass the semantic API configuration:
docker run \
-e MCP_TRANSPORT=http \
-e SEMANTIC_API_BASE_URL=http://host.docker.internal:8000 \
-p 3000:3000 \
legislation-mcpUsage
With MCP Inspector
npm run inspectorAs a Standalone Server
npm startIn Claude Desktop
Add to your Claude Desktop configuration:
{
"mcpServers": {
"legislation-gov-uk": {
"command": "node",
"args": ["/path/to/legislation-gov-uk/build/index.js"]
}
}
}Development
# Watch mode (auto-rebuild on changes)
npm run watch
# Build only
npm run build
# Generate resource manifest
npm run generate-manifest
# Run tests
npm test
# Type-check (run before committing)
npm run checkTest harness
mcp-harness.mjs at the repo root drives a running server over HTTP the way a real MCP client does — useful for exercising a tool end-to-end without the Inspector UI. Start the server with MCP_TRANSPORT=http npm start, then:
# List the tools the server currently advertises
node mcp-harness.mjs --list
# Call a tool with JSON arguments
node mcp-harness.mjs search_powers_and_duties '{"query":"local authority","modality":"duty"}'Set MCP_URL to point at a different endpoint (default http://localhost:3000/mcp).
Architecture
Resources
The server uses a convention-based resource system:
Resources are organized hierarchically in
src/resources/Top-level directories become URI namespaces (e.g.,
clml://,guide://)Build process generates a manifest mapping URIs to files
Resources are loaded on-demand at runtime
Data backends
Most tools proxy the public legislation.gov.uk APIs (src/api/legislation-client.ts), with the advanced-search tools going to the Research API and the semantic tools to the Lex vector service.
The powers-and-duties tools are different: they read a research dataset held in an Aurora Serverless v2 Postgres cluster, queried over the RDS Data API (src/api/duties-db-pg.ts). The Data API is HTTPS-stateless, so there is no connection pool to manage and no shutdown step. The tool layer depends only on the DutiesDbApi interface in src/api/duties-types.ts.
openDutiesPg() returns null when the cluster environment variables are absent, which disables the duties tools rather than failing startup — so local development without AWS wiring works normally. This was previously a SQLite file; that backend was removed once Postgres was confirmed in production (see docs/adr/2026-05-29-postgres-migration-plan.md).
License
Licensed under the Open Government Licence v3.0.
Contains public sector information licensed under the Open Government Licence v3.0.
Author
Available Tools
7 toolsget_legislationARead-onlyIdempotent
Retrieve a full UK legislation document by type, year, and number. Returns readable plain text by default (text). Also available: xml (CLML with full metadata), akn (Akoma Ntoso), html.
Text is best for reading and summarisation. It discards semantic markup, amendment commentaries, and structural metadata — use xml to track amendments, follow cross-references, or check in-force status.
For large documents, use get_legislation_table_of_contents first, then get_legislation_fragment for specific sections.
Common types: ukpga (Acts), uksi (SIs), asp (Scottish Acts), asc (Welsh Acts), nia (NI Acts). type, year, and number must be exact — use search_legislation to confirm if unsure.
Version: use a date (YYYY-MM-DD) for a point-in-time snapshot, or enacted/made/created/adopted for the original version. Do not pass version="prospective"; when metadata lists "prospective", that is the latest version and should be fetched by omitting the version parameter.
See: types://guide, cookbook://point-in-time-version, text://format-guide
Inputs: type (required), year (required), number (required), format, +2 more.
get_legislation_fragmentARead-onlyIdempotent
Retrieve a fragment (section, part, chapter, etc.) of a UK legislation document. Returns readable plain text by default (text). Also available: xml (CLML with full metadata), akn (Akoma Ntoso), html.
Text is best for reading and summarisation. It discards semantic markup, amendment commentaries, and structural metadata — use xml to track amendments, follow cross-references, or check in-force status.
type, year, and number must be exact — use search_legislation to confirm if unsure. Use get_legislation_table_of_contents to discover fragment IDs. Common fragmentId patterns: section/1, part/2, part/1/chapter/3, regulation/5, crossheading/name. The API does not support fragment IDs deeper than the section or regulation level (e.g. section/1/a is not a valid ID).
Version: use a date (YYYY-MM-DD) for a point-in-time snapshot, or enacted/made/created/adopted for the original version. Do not pass version="prospective"; when metadata lists "prospective", that is the latest fragment version and should be fetched by omitting the version parameter.
See: types://guide, cookbook://point-in-time-version
Inputs: type (required), year (required), number (required), fragmentId (required), +3 more.
get_legislation_metadataARead-onlyIdempotent
Retrieve structured metadata for a UK legislation document or a specific fragment (Part, Chapter, section, etc.). More efficient than fetching the full document when you only need metadata.
type, year, and number must be exact — use search_legislation to confirm if unsure.
Returns JSON with: id, type, year, number, title, status (draft/final/revised/proposed), extent (e.g. ["E","W","S","NI"]), key dates (enactmentDate/madeDate), version (label of the returned representation), pointInTime (requested date, when present), versions (available milestone version labels), and unappliedEffects (amendments enacted but not yet applied to the text).
prospective is true when the response contains provisions not yet in force; version says whether the returned version is itself the prospective one. The field is never false, and it is absent on enacted/made text. A whole document requested without a version holds no provision text, so there its absence doesn't mean there are no prospective provisions.
unappliedEffects and upToDate are only present for the latest version (no version parameter). When a specific version is requested, both fields are omitted — effects are not tracked for point-in-time snapshots. For the latest version, upToDate is true when all in-force effects have been applied, false when some are outstanding.
Fragment: pass a fragment to scope metadata to a specific provision (e.g. "section/12", "part/2/chapter/1"). unappliedEffects and upToDate are scoped to the fragment for both revised and enacted/made legislation. Use get_legislation_table_of_contents to discover valid fragment IDs.
Version: use a date (YYYY-MM-DD) for a point-in-time snapshot, or enacted/made/created/adopted for the original version. The returned version field labels the version returned (for fragments, it may be earlier than the requested pointInTime). The versions field may also contain the label prospective; that label identifies the prospective version, which is fetched by omitting version rather than by passing it.
For response field details, see json://metadata-response. For legislation type codes, see types://guide.
For checking geographical extent, see cookbook://check-extent. For retrieving historical versions, see cookbook://point-in-time-version. For determining whether legislation is up to date and which amendments have yet to be applied, see cookbook://check-outstanding-effects.
Inputs: type (required), year (required), number (required), version, +2 more.
get_legislation_table_of_contentsARead-onlyIdempotent
Retrieve the table of contents for a UK legislation document. Returns structured JSON by default (json). Also available: xml, akn, html.
Shows the hierarchical structure (Parts, Chapters, Sections) with headings and fragment IDs for use with get_legislation_fragment.
meta.prospective is true when the response indicates that the document contains provisions not yet in force. It is left out on enacted/made text. Contents entries are marked inconsistently, so its absence doesn't mean there are no prospective provisions.
type, year, and number must be exact. If you're not certain, use search_legislation to confirm — identifiers guessed from general knowledge are often wrong.
Version: use a date (YYYY-MM-DD) for a point-in-time snapshot, or enacted/made/created/adopted for the original version. Do not pass version="prospective"; when metadata lists "prospective", that is the latest version and should be fetched by omitting the version parameter.
See: types://guide, cookbook://point-in-time-version, json://table-of-contents-response
Inputs: type (required), year (required), number (required), format, +2 more.
get_resourceARead-onlyIdempotent
Fetch a resource by URI. For agents that cannot access MCP resources directly, use this tool to retrieve guides, reference material, and documentation.
Available resources:
guide://getting-started— Overview and quick startguide://troubleshooting— Common errors and edge casescookbook://index— Index of all cookbook recipescookbook://check-extent— How to check geographical extentcookbook://point-in-time-version— How to retrieve historical versionscookbook://semantic-search-workflow— Semantic search step-by-step (needs the semantic search backend)types://guide— All UK legislation type codes (ukpga,uksi, etc.)types://data— Type codes as JSONyears://regnal— Regnal year identifiers for pre-1963 legislationtext://format-guide— Plain text output format documentationclml://schema-guide— CLML XML structure referenceclml://metadata/extent— Geographical extent in CLMLatom://feed-guide— Atom feed format for search resultsjson://search-response— search_legislation response formatjson://metadata-response— get_legislation_metadata response formatjson://table-of-contents-response— get_legislation_table_of_contents response formatjson://semantic-search-response— search_legislation_semantic response formatjson://semantic-section-response— search_legislation_sections_semantic response format
Inputs: uri (required).
search_effectsARead-onlyIdempotent
Search for legislative effects (amendments, repeals, insertions, etc.) by source and/or target legislation.
Use source parameters to find effects made BY a piece of legislation (e.g. "what did Act X amend?"). Use target parameters to find effects made TO a piece of legislation (e.g. "what amends Act Y?"). You can combine both to find specific effects between two pieces of legislation.
For step-by-step examples, see cookbook://search-effects. For legislation type codes, see types://guide.
Inputs: page, applied, sourceType, sourceYear, +4 more. Returns: meta, effects
search_legislationARead-onlyIdempotent
Search for UK legislation by keyword, title, or other criteria on legislation.gov.uk. Returns JSON by default (set format="xml" for raw Atom feed).
Results include: id, type, year, number, title, and date. Use q for full-text keyword search, title for title search. Filter by type, year, startYear/endYear range, subject, department, extent, or language. Use sort to order results. Returns 20 results per page — use page to paginate; check meta.morePages in the response.
subject only applies to SI-family types (uksi, ssi, wsi, nisr, etc.); Acts don't carry subject metadata. If subject is set without a type, secondary is used by default.
See: types://guide, json://search-response, atom://feed-guide
Inputs: q, page, sort, type, +10 more.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 7 tools
The four retrieval tools (get_legislation, get_legislation_fragment, get_legislation_metadata, get_legislation_table_of_contents) share a prefix but each description clearly states its role and even prescribes a workflow (TOC first, then fragment; metadata instead of full document). search_legislation vs search_effects are cleanly separated by domain. Minor residual risk that an agent fetches a whole document instead of metadata/TOC, but the guidance largely prevents that.
Every tool follows a strict verb_noun snake_case convention: get_legislation*, search_legislation, search_effects, get_resource. The get_legislation_* family is a predictable, extensible namespace that makes the hierarchy legible.
Seven tools is well-scoped for a legislation retrieval domain: one search tool, one document example, three scoped retrievals, one effects search, and one documentation fetcher. Nothing looks redundant or superfluous.
Covers the core lifecycle: discover (search_legislation), navigate (TOC), retrieve (document/fragment), inspect (metadata), and trace amendments (search_effects). Gaps are modest: no tool to enumerate legislation types or available versions directly, and resources reference search_legislation_semantic / search_legislation_sections_semantic tools that are not actually exposed, which could dead-end an agent following the cookbook.
Maintenance
Related MCP Connectors
Search and read UK legislation at any date, resolve citations, list amendments, track changes.
Search UK Acts, Statutory Instruments, and legislation with full text retrieval
Search and read all UK legislation (130k Acts and regulations), updated daily, with official links.
Provenance-backed EU and UK legislation for AI agents, addressable to the individual provision.
Related MCP Servers
- AlicenseAqualityBmaintenanceProvides comprehensive tools for searching UK case law, legislation, parliamentary Hansard debates, and HMRC tax guidance. It features a specialized OSCOLA citation parser to extract and resolve legal references directly from text.36474 PyPI21MIT
- AlicenseAqualityBmaintenanceEnables searching and retrieval of UK legislation (Acts, Statutory Instruments) from legislation.gov.uk with persistent identifiers and verifiable citations.971 PyPIApache 2.0

Legalizeofficial
AlicenseNot gradedqualityCmaintenanceEnables AI assistants to search and read consolidated legislation from multiple countries, retrieve exact law texts as of any historical date with citations and git commit SHAs, and create webhook or email subscriptions to track legal changes.2MIT- AlicenseNot gradedqualityCmaintenanceEnables querying point-in-time amendment history for UK law, including searching provisions, viewing provision histories, listing recent amendments, and identifying most-amended provisions.1MIT