Skip to main content
Glama
nyc-charter-laws-rules

nyc-charter-laws-rules

nyc-charter-laws-rules

The single place to access, process, and query New York City's three primary legal documents:

  • The New York City Charter

  • The New York City Administrative Code

  • The Rules of the City of New York

This repo includes:

  • A MCP (Model Context Protocol) server so AI assistants can query the documents directly

  • Scripts to fetch and parse the latest bulk XML from American Legal Publishing

  • A committed JSON index (data/index/json/) for machine use

  • A committed Markdown index (data/index/markdown/) for human browsing — readable directly on GitHub

  • A site structure (data/structure/) for the coming law website: each section's subdivisions, cross-reference targets, and chapter and title names, built with the index (see Site structure). It is not in the npm package.

  • A website, the BetaNYC Law Reader: the Charter, one page per section, with links between sections and search, built from the index by npm run build-site (see The website). .github/workflows/deploy-site.yml builds it and publishes it to law.beta.nyc on GitHub Pages; the HTML is never committed. It is not in the npm package.

Clone the repo and everything is ready to use. No setup required to browse or query the current index. Run npm run fetch-data && npm run build-index only when you want to refresh from AML.

Vibe coded with Claude by BetaNYC.

What's changed: new tools, corrections and other changes a reader would notice, newest first. Daily law text updates are in CHANGELOG.md.


API key

No API key is required. The Charter, Administrative Code, and Rules are served from an offline corpus bundled with the package, so this server works out of the box — no signup, no token, no environment variables to set.

The bundled text is as of the release. An npm install carries the law text from the day that version was published. When the daily refresh picks up new law text, it also publishes a new patch release automatically (see Releases), so the law text in npx -y @betanyc/nyc-charter-laws-rules is normally at most a day behind main's. Code changes ship with the next release. Automatic releases pause while a hand-bumped version is waiting to be published or a release run has failed. get_version reports the dates you are actually serving. To serve main's index directly, see Getting current law text.


Related MCP server: new-york-code

What it does

Exposes 8 tools over MCP:

Tool

Description

search

Keyword search across all three documents (short keyword queries work best)

get_section

Retrieve a specific section by citation (e.g. § 259, Chapter 11)

list_titles

List the chapters of a document, in order

get_title

List the sections in a chapter, or in an Administrative Code title (citation and heading of each)

get_version

Return the currency date for each document — so responses can be grounded in exactly how current the law is

whats_changed

What changed in this server, newest first, from WHATS-CHANGED.md: new tools and corrections

about_betanyc

Who built this server, where its code is, and where to report a bug in this server or ask for a new feature

about_data

Where the law text comes from, from DATA-SOURCES.json: the publisher, whether it is the official text, when this server's index was built, where to check a section and how to report an error


Tools reference

Every law-text answer (search, get_section, list_titles, get_title) ends, before the disclaimer, with a source line per document it came from. It says that BetaNYC converted the text and how, so it is not the official text; the date of this server's copy; and the official record, with its publisher and a link to the code library. search adds that snippets are cut at 400 characters. Under it is the publisher's own "current through" line from the same copy, exactly as the publisher gives it. For example:

BetaNYC modified this data: converted by BetaNYC from the publisher's bulk XML files: line breaks are collapsed, so tables run together; the publisher's editing markers are removed and character codes decoded; citations are worked out by BetaNYC from headings and can be wrong or cut short. This copy should not be considered the official record. As of 2026-11-14T11:05:40.153Z (the date of the copy this server answers from). Official record: New York City Charter, bulk XML download (American Legal Publishing), https://codelibrary.amlegal.com/codes/newyorkcity/latest/NYCcharter/0-0-0-1
The publisher's own "current through" line for it, as given: "Current through Local Law 2026/164, enacted November 10, 2026,"

get_version reports dates and counts, not law text, so its lines start Source: … (American Legal Publishing). and end with Link:. The wording of both kinds comes from the shared module's provenance().

The copy date is indexedAt in versions.json. It moves only when the text changes, so a copy can be days old and still match the publisher's latest download. The index keeps no date for when the source was last checked, so none is shown. Answers that find nothing ("No results found", "Section not found", "No titles found", "No sections found") say which documents were searched and carry the same lines.

Anything an answer repeats from the request (a query, citation, title, parameter name or value, or tool name) is cut to one line of at most 100 characters, ending …. If an index file is missing or unreadable, the answer names the document and says the server's operator should reinstall the package or rebuild the index; the file path goes to the server's stderr, not to the answer.

Every list says how much of how many it shows when it does not show everything, and how to get the rest.

Every tool only reads, and answers from the index bundled with the package, never a live API. Each says so in its MCP annotations (readOnlyHint: true, openWorldHint: false).

Keyword search across the NYC Charter, Administrative Code, and Rules. It is keyword matching, not a question-answering engine, so short keyword queries work best: sidewalk shed rather than "How long can a sidewalk shed stay up?"

  1. Phrase first. The whole query is matched as typed (case-insensitive). Quotes around the whole query, straight or curly, are removed first, so "open data" and open data search the same phrase. If any section contains it, those results are returned, relevance-ranked: heading matches rank above citation matches, which rank above body-text matches, and whole-word matches rank above substring matches.

  2. Terms, if the phrase finds nothing. Question words and common words (how, what, can, a, the, up, about, …) are dropped. The full list is SEARCH_STOPWORDS in src/corpus.ts. Each remaining term matches at the start of a word, with a trailing plural s ignored, so tanks finds "tank" and shed does not find "established". There is no check at the end of a word, so car also finds "carbon"; that is what lets appoints find "appointed" (a whole-word check was tried and lost an eval question). Every section with at least one term gets one score, and results are sorted by it alone (termScore in src/corpus.ts):

    • a rare word counts more than a common one (its weight is the log of sections searched divided by sections that contain it);

    • a word in the heading or citation counts 3 times;

    • a long section is pushed down a little: the score is divided by 1 + log(1 + length / average length);

    • the score is multiplied by the share of the words' total weight the section covers, so a section with the rare words beats one with only the common ones;

    • sections under 100 characters (empty headings, [Repealed]) count 0.3 times, and Local Law appendix records (heading like L.L. 2016/002) half.

    So a section with every word can rank below one with fewer, rarer words in its heading. Through 0.5.x, a section with more of the words always came first, before any weight applied, so long definitions sections that happen to hold every word won.

  3. Said out loud. When step 2 runs, the first line of the response says so and lists the terms:

    • every result contains every term: No section contains the exact query; showing sections containing all of: building, owners, required, drinking, water, tanks.

    • some results lack a term, and no section anywhere has every term: No section matched every term; showing sections matching some of: smoking, banned, nyc.

    • some results lack a term, and at least one section has every term: No section contains the exact query; showing the best matches for some or all of: long, sidewalk, shed, stay.

  4. How many. For a phrase match, when more sections matched than limit, a line after the results says Showing 10 of 35 matching sections, best first. and how to see others. When step 2 ran, sections with every term and sections with only some are counted apart, for example 1 section contains every term; it does not rank in this list. To see more of them, raise limit (max 50), … then 1525 other sections contain only some of the terms; the 10 shown are the best-ranked of those. When no section has every term: 619 sections contain some of the terms; the 10 shown are the best-ranked of those. The response never suggests raising limit to see sections that hold only some of the words. Each snippet is cut at 400 characters, marked …, and a line says so; get_section returns the full text.

This is still keyword matching: a question whose answer uses other words ("warm" and "winter" for a section about minimum temperatures) does not find it. See Evaluation set.

Parameter

Type

Required

Default

Description

query

string

yes

—

Search term or phrase

corpus

string

no

all

charter, admin_code, rules, or all

limit

integer

no

10

Max results (1 to 50)

search("open data")
search("landlord inspection", corpus="admin_code", limit=20)
search("board of health", corpus="rules")
search("How long can a sidewalk shed stay up?")   # term fallback; first line says so

get_section

Retrieve a specific section by citation or heading fragment. Input is normalized (with or without §, any case, extra whitespace). If the same citation exists in more than one document (e.g. charter Chapter 3 vs a rules chapter, or a rules section number repeated across titles), a disambiguation list is returned — re-run with the corpus parameter. The list shows at most 25 matches and says how many there are.

Parameter

Type

Required

Description

citation

string

yes

Section citation or heading (e.g. § 259, Section 20-f, 11-602.1, Chapter 11)

corpus

string

no

charter, admin_code, or rules (default: all three)

get_section("§ 259")
get_section("11-602.1")
get_section("Chapter 11", corpus="charter")

list_titles

List the chapters of a document, in order, each with its heading. The first line says how many there are (84 chapters, in order.); lists longer than 200, such as the Administrative Code (350) and the Rules (over 700), come in pages, and the first line says, for example, Showing 1 to 200 of 731. Call again with offset 200 for the next ones.

Each title of the Administrative Code has its own Chapter 1, so Administrative Code chapters are shown with their section range: Chapter 1 (§ 3-101 to § 3-196) — Chapter 1: Mayor, sorted by first section. The index does not record which title a Rules chapter is in, so several Rules chapters share a number; their headings tell them apart. Through 0.6.0 the list came in no order, and lettered chapters showed a cut number (Chapter 18- for Charter Chapters 18-A to 18-D).

Parameter

Type

Required

Description

corpus

string

yes

charter, admin_code, or rules

limit

integer

no

Max titles to return (default 200, max 1000)

offset

integer

no

How many to skip, for the next page (default 0)

list_titles("charter")
list_titles("rules")

get_title

List the sections in a chapter: the chapter's heading, then the citation and heading of each section, in order. Use get_section for a section's text. Numbers match whole: Chapter 1 is not Chapter 10 or Chapter 1-A. A number several chapters share (an Administrative Code or Rules Chapter 1) gives each of them.

The Administrative Code's titles are not in the index, but its sections are numbered by title (§ 24-163 is in Title 24), so Title 24 gives every chapter whose sections are numbered 24-…, and Title 3, Chapter 1 narrows to the chapters numbered 1 among those. A lettered title shares its parent's numbers (Title 16-A's sections are § 16-501 on), so Title 16 brings Titles 16-A and 16-B too. The Charter has no titles, and the index does not record Rules titles, so ask for a chapter there.

The index is flat: each source file keeps its records in document order, and a chapter is its heading record plus the records after it, up to the next chapter heading. Through 0.6.0 this tool returned only the chapter's heading record, and Title 6 found nothing.

Parameter

Type

Required

Description

corpus

string

yes

charter, admin_code, or rules

title

string

yes

A chapter (Chapter 11), or in the Administrative Code a title (Title 6) or both (Title 3, Chapter 1)

limit

integer

no

Max records to return (default 200, max 1000)

offset

integer

no

How many to skip, for the next page (default 0)

get_title("charter", "Chapter 11")
get_title("admin_code", "Title 6")
get_title("admin_code", "Title 3, Chapter 1")

get_version

Return the currency date for each document. Each corpus updates on its own schedule — the Charter and Administrative Code track enacted local laws, while the Rules update independently as agencies adopt new rules.

No parameters required.

get_version()

Example response:

NYC Charter:           Current through Local Law 2026/112, enacted June 19, 2026, (854 sections; indexed 2026-06-29T12:33:00.864Z)
Administrative Code:   Current through Local Law 2026/112, enacted June 19, 2026, (12587 sections; indexed 2026-06-29T12:33:09.801Z)
Rules of NYC:          Current through rules effective July 1, 2026. (8671 sections; indexed 2026-07-01T12:43:45.635Z)

whats_changed

What changed in this server, newest first, from WHATS-CHANGED.md, which ships with the package. Covers new tools, corrections and other changes a reader would notice; daily law text updates are not listed (see CHANGELOG.md). Corrections say what to re-check if you used the old answer. Returns text plus structuredContent matching the tool's outputSchema.

Parameter

Type

Required

Description

since

string

no

YYYY-MM-DD: changes on or after this date

tag

string

no

Site, Data, MCP or Correction (any case)

limit

integer

no

1 to 50, default 10

whats_changed()
whats_changed(tag="Correction")

about_betanyc

Who built the server (BetaNYC, a project of the Fund for the City of New York), its version and repository, where to report a bug in this server or ask for a new feature, and links to BetaNYC. No parameters.


about_data

Where the law text comes from, answered from DATA-SOURCES.json, which ships with the package. There is one source per document (charter, admin-code, rules), each from American Legal Publishing's bulk XML download, the code library the NYC Law Department contracted for. For each it gives the publisher and link, whether it is the official text (the source is; this server's text is not, because the build cleans it, so figures_official is false), how it reaches this server, what BetaNYC changed, when this server's index was built for that document (read from versions.json at run time; get_version gives the publisher's own "current through" line), where to check a section, how to report an error in the text or in this server, and the corrections that touched it. Questions about the data go to BetaNYC at lab@beta.nyc. Returns text plus structuredContent matching the tool's outputSchema.

Parameter

Type

Required

Description

topic

string

no

charter, admin-code, rules, or a tool name such as search; all or nothing returns every source

about_data()
about_data(topic="rules")

data.json is a DCAT-US 3.0 catalog generated from DATA-SOURCES.json (python3 scripts/whats_changed.py about-data catalog DATA-SOURCES.json); never edit it by hand.

whats_changed, about_betanyc and about_data are the three tools BetaNYC adds to each of its MCP servers. src/betanyc-tools.ts is a copy of the canonical file in BetaNYC's workspace (shared module 1.5.2); never edit the copy. Their text ends with the one-line disclaimer (the full one with NYC_CLR_FOOTER=full), and they do not use up the full footer meant for the first law answer.


Testing and CI

Running tests

npm test

npm test builds the TypeScript source first (pretest script), then runs the full suite with node --test. Every test file in the table below runs together, except the browser tests for the website, which run on their own (npm run test:site; run npx playwright install chromium once first). On a laptop the whole run, build included, takes about 4 seconds (measured October 2026).

Test layers

File

What it covers

test/extract-text.test.js

Unit tests for the extractText, normalize, childrenByTag, getAttr, and tagOf helpers in scripts/lib/extract-text.js. Covers inline-LINK document order (issue #3 regression), entity decoding, ALP-marker stripping, enumeration-marker repair, empty/self-closing elements, deep nesting, whitespace-only text nodes, and helper edge cases.

test/content-leak.test.js

Regression tests for the content-leak fix (PR-A0): undecoded &#160; nbsp entities, [ALP S-xxx] editorial markers, and leading-digit run-ons (1Each). Includes scope guards confirming that inline labels with no <TAB/> after them in the source ((6)the) are left untouched.

test/corpus-invariants.test.js

Invariant assertions over the committed data/index/json/*.json (every section across charter, admin_code, and rules). Asserts: no run-together text, no subdivision label fused to the next word (a.There, issue #27), no leaked XML tags, no undecoded entities, no double spaces, no leading/trailing whitespace, and structural integrity against versions.json counts. Collects all violations before asserting, with corpus/id/citation/snippet in the failure message.

test/mcp-tools.test.js

In-process tests for the MCP handler functions (searchCorpus, getSection, listTitles, getTitle, getVersions) imported from dist/corpus.js. Grounded in real index data: verifies § 292 text content (the issue-#3 corrected phrase), negative lookups, version presence, and title listing.

test/search-fallback.test.js

Plain-language questions (issue #30). Unit tests for stopword and question-word stripping (queryTerms) and surrounding-quote removal (stripSurroundingQuotes). Exact ranks, counts and first-line notices run against a synthetic 8-section index committed at test/fixtures/search-index/, served through NYC_LAWS_INDEX_DIR in a child process: ranking, word-start matching (shed is not found in "established"), plural s, the all-terms and widened notices, phrase results unchanged, quoted queries matched as phrases, and the count line after a fallback (searchCountLine), which counts every-term and some-term matches apart and never suggests a higher limit for the weak ones. Against the real index only behavior is checked (fallback used, notice first, terms listed, results non-empty), so a daily refresh cannot turn it red.

test/search-ranking.test.js

How the word fallback ranks (round 2 of #49): termScore one factor at a time (heading 3 times, rare over common words, long sections pushed down a little, short stubs 0.3, Local Law appendix records 0.5), and on a synthetic index at test/fixtures/ranking-index/ a short section about the question outranks a long definitions section holding every word. The notice and count lines never say no section has every term when one does, even off the page. Phrase search and get_section lookups on the round-1 fixture return exactly what the 0.6.0 code returned (recorded).

test/chapters.test.js

list_titles and get_title (live check of 0.6.0): Charter chapters once each, in order, with whole numbers (Chapter 18-A to 18-D, not Chapter 18-); Administrative Code chapters told apart by section range; get_title lists a chapter's sections (Charter Chapter 70, Chapter 1 from § 3 to § 20-w), Title 6 and Title 24 give the Administrative Code chapters numbered 6-… and 24-…, Title 3, Chapter 1 narrows to the Mayor's chapter, a Rules title says to ask for a chapter, and other queries still match by prefix. Holds on an index built before or after the label fix.

test/echo-and-paths.test.js

A missing or unreadable index file (through a broken NYC_LAWS_INDEX_DIR) names the document, never the path, and writes the path to stderr; echo() cuts what the caller sent to one line of at most 100 characters, for a 5,000-character query, citation, title, parameter name, corpus value and tool name, and for fake stack-trace lines.

test/index-dir.test.js

The NYC_LAWS_INDEX_DIR override (issue #26), each case in a child process: unset and blank serve the bundled index; a set directory serves its versions and section text; relative paths resolve against the working directory; a directory without versions.json fails at startup naming the variable, with no silent fallback. Also starts the server over stdio and checks that serverInfo.version matches package.json and that get_version reports the override.

test/footer-modes.test.js

Disclaimer footer modes (issue #25). NYC_CLR_FOOTER parsing (unset, blank, both modes, a typo falling back to full with a warning); the default sending the full footer once and the one-line footer after; full sending it every time; not-found, empty and error responses carrying a disclaimer; and the invariant that every response in every mode, including an unrecognized one, says "legal advice". Also starts the server over stdio to check instructions, the first and second responses, and the single stderr warning.

test/strict-schema.test.js

Strict tool schemas (issue #19). Asserts every tool in TOOLS (from dist/tools.js) advertises additionalProperties: false, and that callTool() rejects an undeclared parameter with an error naming both the offending key and that tool's accepted keys — rather than silently dropping it and returning unfiltered results. Includes regression guards that valid calls, with and without optional params, still succeed. Also checks that the schemas generated from zod (issue #22) keep each tool's parameters, required set, choices and descriptions, and that search's limit advertises the 1 to 50 the server enforces.

test/annotations.test.js

Every tool carries annotations (assertEveryToolAnnotated): readOnlyHint: true, openWorldHint: false (all answers come from the bundled index) and a title, in TOOLS and in tools/list over stdio (issue #38).

test/tool-size.test.js

The tools/list JSON plus the server instructions stay under a size budget (toolListSize), with a dated note for each raise (issue #44), and no sentence, such as the disclaimer, is repeated across the law-text tool descriptions (issue #48).

test/errors.test.js

Every failure (bad parameter values, a missing parameter, an unknown parameter or tool) is isError with a plain sentence that names what to fix and lists the accepted parameters, with no zod JSON or stack frames, and keeps the disclaimer (issue #46).

test/fetch-retry.test.js

politeFetch in scripts/lib/fetch-retry.js, the download behind fetch-data, against a fake fetch: User-Agent with the package version, a timeout, up to two retries on 429 and 5xx honoring Retry-After, none on a 404 (issue #39).

test/provenance-lists.test.js

Every law-text answer has a source line per document (publisher, the indexedAt date from versions.json, a code-library link) before the disclaimer (issues #40, #41), that says BetaNYC converted the text for the four law-text tools and stays a plain Source: line for get_version, each followed by the publisher's "current through" line exactly as get_version shows it, also on answers that find nothing (with which documents were searched; the empty list_titles case runs on the synthetic fixture); search says how many matched and that snippets are cut; list_titles pages through all of the Rules with offset; get_title pages by 200 by default and honors limit and offset; the get_section match list stops at 25 and says how many there are (issue #42). DATA-SOURCES.json lists wrong or cut-short citations as a known gap. Loose bounds only, against the committed index.

test/index-checksum.test.js

Each bundled data/index/json/<corpus>.json matches the sha256 that build-index.js recorded in versions.json, and mergeVersions() keeps it and moves indexedAt when only the text changed (issue #45).

test/stdout.test.js

Starts the built server with a bad NYC_CLR_FOOTER, makes four calls, and checks that every stdout line is a JSON-RPC 2.0 message and the startup warning went to stderr (issue #47).

test/build-smoke.test.js

Build pipeline smoke test (Layer 5a). Feeds tiny hand-authored AML-shaped XML fixtures to the pure builder buildSectionsFromXml in scripts/lib/build-corpus.js — no multi-MB ZIPs. Asserts correct section shape, citation derivation (Section 292. → § 292; a label with a period inside, such as L.L. 2016/002, G.1.2 or 10-1104.1, kept whole; a chapter's whole number, such as Chapter 18-A or Chapter 19.1, read only at the start of the heading), clean text (no tags/entities/edge whitespace), document-order LINK extraction, and that non-qualifying records (wrong style-name, too-short heading) are filtered out.

test/structure.test.js

The site structure (issue #61), on American Legal's own XML: the 44 Charter fixtures in test/fixtures/diff/xml/, 4 Rules files in test/fixtures/structure/rules/ and 2 in test/fixtures/structure/rules-edge/. The structure hooks leave the index alone (the fixtures' JSON and Markdown hash to what v0.6.2 wrote, pinned in the test); every block is a slice of its section's text and the blocks joined with one space are the text; Charter § 1133 keeps labels, depths and anchors ((b)(1)); a label repeated in one section gets (a)(1)-2; a Charter link resolves to its section and a link into a document not built keeps its name; a Rules chapter with no Title record around it takes its title from the publisher's key (#59), and one with no match is left without a title; a link to an anchor id or name the publisher put on two records is left unresolved and marked ambiguous (Rules § 2-01 and § 2-01.1); block text is the index's text byte for byte, with no Unicode normalization (the micro sign in Rules § 40-05). When data/structure/ is present, each file must carry the sha256 of the committed index JSON and versions.json, and slice its text exactly.

test/site-build.test.js

The website build (issue #62), from the 44 Charter fixtures, without the Pagefind index: a page for every record, matching versions.json; chapters in the book's order, not the ZIP's; a unique title, description and canonical on every page and no repeated id; every American Legal id in redirects.json, every subdivision anchor and every link in the law text resolves (and an old path with an id on the end still redirects); every description at most 160 characters; the bottom box on every page but About, its "current through" line attributed to American Legal Publishing (a publisher line that does not start "Current through" stops the build); on every law page a source box that links to that record's own page at American Legal Publishing, and a footer without the "comes from American Legal Publishing" sentence, which every other page keeps; the footer's download link goes to data/index; the chapter pager names chapters as the lists do; the top bar's aria-current; the About page's disclaimer equals the server's FOOTER without its last line, and a FOOTER with a different last line stops the build; the About page has its sections in order, a jump list that names each one, the history links, the copy review's wording (with the serial comma), no warning before the Disclaimer section and no bottom box, the disclaimer last, and lab@beta.nyc as its contact; the Markdown and the HTML show the same blocks in the same order (for every Charter section too, when data/structure/ matches the committed index); structured data uses only schema.org properties (the list in test/fixtures/site/schema-org-30.1.json); sitemaps, robots.txt and noindex; the jump box; the New York clock; law.css names no colors, and every font family it names, in font-family or a font shorthand, is the template's var(--font-body) or var(--font-head) (planted Arial, system-ui, Georgia and quoted families prove the check fails); every chapter, section and shared-number page has one side list in a closed fold, with every chapter in order and only its own chapter open (aria-current), before <main> (and all of the full Charter's chapters on § 259's page, against the committed index), and the contents page has none; on every page with breadcrumbs the first is "Home", and on every indexed page the structured data names the same crumbs; the search box is on the home and search pages only, with its hint as placeholder text; the template copies are unchanged and their color pairs pass contrast (focus ring 3:1 on every background, text 4.5:1); the build refuses mismatched data and never clears a folder it did not make.

test/deploy-workflow.test.js

The website's deploy workflow (issue #64), read as text: it runs on a push to main and on workflow_dispatch, nothing else; every file the site build imports (walked from scripts/build-site.js) or reads (src/tools.ts, DATA-SOURCES.json, the index, the structure, the lockfile) is in its push paths; only main builds; pages: write and id-token: write only on the deploy job; one deployment at a time; npm test and build-site run before the upload; the smoke check reads the deployed URL. And that refresh-data.yml dispatches it only when its commit step pushed, as its last step.

test/site/site.test.mjs

Run by npm run test:site, not npm test. Builds the fixture site with its Pagefind index, serves it on 127.0.0.1 and opens it in headless Chromium. Reads the accessibility tree (aria snapshot, getByRole, and Chromium's computed role and name for every focusable element, inside NYSDS's shadow roots too) on every page type (home, contents, chapter, section, shared number, search with results, About, 404) at desktop and phone width, and fails if a control has no name, two controls share a name, one link name goes to two places, or something takes focus with no role or name; a planted duplicate, an unnamed button and a <span tabindex="0"> prove the check fails. No page scrolls sideways at 320px. In forced colors a focused search box shows a ring. The search box is only on the home and search pages, named by its label, with placeholder text at 4.5:1 or better. The side list holds every chapter with the current one open and the current section marked, has a visible "Charter chapters" heading on a wide screen and folds behind one closed button, one tab stop, above the breadcrumbs on a phone, comes before the law text with the skip link passing it, reads with JavaScript off (folded on a phone, so the heading and text start within the first screen at 390px), and scrolls itself (not the page) to the reader's own section, tested on the last section of the fixtures' longest chapter, or else to the open chapter; Shift+Tab up the list never leaves a focused link under the sticky heading. The first breadcrumb is "Home" and the trail lines up with the heading. No law page scrolls sideways from 320px to 1920px wide; the law text is in the body font on screen and in print. Also: section text and the bottom box with JavaScript off, citation jumps (Enter and the Go button, a subdivision, a shared number), word search (snippets, sub-results, paging, filters), Copy citation, the print stylesheet, the skip link, the 404 redirect, and that nothing loads from outside the site.

test/markdown-parity.test.js

Rebuilds each committed data/index/markdown/<corpus>.md from the committed JSON (and the committed structure, when there is one) with scripts/lib/serialize-markdown.js, and compares every byte, for every section of all three documents.

test/build-idempotence.test.js

A rebuild with no source change must leave every tracked output byte-identical. Unit tests for mergeVersions() in scripts/lib/merge-versions.js (an unchanged corpus keeps its prior indexedAt; a changed currentThrough or sectionCount adopts the fresh one; re-merging is a fixed point), plus two runs of scripts/update-changelog.js against a temporary tree, asserting the second leaves versions.json, changelog.json, CHANGELOG.md and README.md unchanged. ZIP-free, so it runs in CI.

test/auto-release.test.js

Unit tests for the pure helpers in scripts/auto-release.js: finding the bump commit, shortening AML "current through" lines, listing which corpora moved, and the release-entry text. Starting values are pinned in the test, not read from live data.

test/betanyc-tools.test.js

whats_changed and about_betanyc: advertised read-only and strict with an outputSchema; every entry in this repo's WHATS-CHANGED.md valid and returned; filters; bad arguments rejected by name; every Correction carrying advice; the disclaimer on both, without using up the full footer; and both answers accepted by the MCP SDK client over stdio against their output schemas. Depends on no law text and no package version, so a daily refresh cannot turn it red.

test/about-data.test.js

about_data: every tool has a source in DATA-SOURCES.json (assertEveryToolExplained, so a new tool cannot ship unexplained); one source per document, from American Legal Publishing, with figures_official false because BetaNYC cleans the text; each document's date read from the versions.json being served, and "unavailable" when an index has none; BetaNYC's contact address; the disclaimer; and the answer accepted by the MCP SDK client over stdio against its output schema. Depends on no law text and no package version.

test/whats-changed-release.test.js

The What's changed release gate end to end, in a throwaway git repo with a stub npm (needs python3; skips without it): a hand bump waiting for its tag (refresh commits data without a bump, CI passes, the gate fails), release day (both headings dated in one commit; the gate and the append-only check pass), the next automatic release (no entry needed, gate passes), and an Unreleased entry beside a published version (refresh commits data, prepares no release, goes red; CI rejects it).

test/auto-release-cli.test.js

End-to-end runs of scripts/auto-release.js prepare and ensure against a throwaway git repo with stubbed npm and gh: version bump, tagging, one release dispatch, and recovery from a depth-1 checkout. The fixture pins the version (0.3.0) and the Rules "current through" date (October 4, 2026), so it does not drift when real releases ship or the law text moves.

Evaluation set

eval/questions.json holds realistic questions with known answers in the law text (which section sets up the Independent Budget Office, where the Open Data Law is, how long a sidewalk shed can stay up), written on 2026-11-18 before the first scoring run. npm run eval runs them offline against the bundled index; npm run eval -- --save also writes the results to eval/runs/ (--save=NAME for a named run, --note=TEXT to say what it is for), and never overwrites an earlier run. It is not part of npm test: run it before a minor release and keep the result.

Results so far, all on 2026-11-18:

  • 11 of 12 on the first set (eval/runs/2026-11-18.json). Q10, the plain-language sidewalk-shed question, missed Administrative Code § 28-220.1 in the top 10.

  • 12 of 17 after five questions asked the way a person would ask, with no citation (Q13 to Q17), were added and Q09 was made to check the penalty amounts it asks about (review-fixes, and the same again in round2-before). Q10, Q13, Q14, Q15 and Q16 failed. The cause was not missing word weights, as first written: the word search ranked any section with more of the question's words first, before its weights applied, so long definitions sections won.

  • 15 of 17 with the ranking described under search (round2-after). Q10, Q13 and Q16 now pass, and no question that passed before fails. Two still fail, and keyword ranking cannot fix them: in Q14 ("How warm does my landlord have to keep my apartment in winter?") the right section, Administrative Code § 27-2029, "Minimum temperature to be maintained", contains none of the question's words. In Q15 ("Where is smoking banned in NYC?") § 17-503 does contain "smoking", but so do 127 other sections, and it lacks "banned", the rarest word, which 8 other sections have. With the rest of that round's fixes the result is the same, 15 of 17 (round2-final).

Differential test (Layer 4 — occasional cadence)

A cross-engine differential test compares our JS extraction against an independent Python reference over 44 committed charter XML fixtures. It is not part of npm test — it runs only when explicitly invoked:

npm run test:diff

The test shells out to python3 (stdlib xml.etree.ElementTree + itertext()) and asserts that both engines agree on normalized section text for all 393 sections across the fixture set. If python3 is not on PATH, the test skips gracefully rather than erroring.

The fixtures live in test/fixtures/diff/xml/ — 44 files selected deterministically (every 2nd file by sorted filename from data/raw/charter/XML/, always including 0-0-0-1277.xml). They are committed to the repo so the test runs in CI without downloading ZIPs.

Calibrated baseline (2026-06-02): 393/393 sections agree after the comparison normalizer. One intentional formatting difference is neutralized before comparing: the JS path appends a trailing space after standalone digit-dot enumeration markers ("1.") to restore a formatting separator that empty <TAB/> elements drop; Python's itertext() returns raw source text. Both are faithful to the source; the space is a readability aid. The comparison normalizer collapses "N. " → "N." on the JS side so the comparison tests token order and content only. No allowlist entries are required.

Continuous integration

.github/workflows/test.yml runs npm ci && npm run build && npm test on every pull request and push. Node matrix: 20.x and 22.x. The manifest declares engines.node ">=20" — a floor only; the server uses no APIs newer than Node 20, so newer Node releases are supported even though CI tests the 20.x/22.x pair. Node 18 was dropped because it reached End-of-Life on 2025-04-30; the manifest previously declared >= 18 but CI never tested it.

.github/workflows/test.yml also runs a What's changed job: node scripts/auto-release.js check-whats-changed --base-ref <merge base with main>. It validates WHATS-CHANGED.md with scripts/whats_changed.py (copied unchanged from BetaNYC's workspace; never edit it here), checks that old entries are only ever added to, that a version bump in a pull request has an entry, and that an ## Unreleased: entry comes with a hand-bumped, undated release in RELEASES.md.

It also runs an About data job: python3 scripts/whats_changed.py about-data check DATA-SOURCES.json --tools-file <the built server's tool list> (every tool has a source, the file has no errors), about-data catalog DATA-SOURCES.json --check (data.json is current), and the JSON Schema and DCAT-US 3.0 validators (scripts/tests/catalog_validate.py, with jsonschema==4.26.0, referencing==0.37.0 and rfc3987==1.3.8 pinned through uv). release.yml runs about-data check --release before npm publish.

It also runs a Charter site job: npm run test:site in Chromium, and, once the daily refresh has committed data/structure/, npm run build-site over the whole Charter. That job deploys nothing; deploying is deploy-site.yml (see Deploy).

.github/workflows/differential.yml runs npm run test:diff on manual dispatch (workflow_dispatch) and nightly at 03:00 UTC. It is intentionally off the per-PR/per-push path. Python matrix: 3.11 and 3.12 (covers the team's 3.11–3.14 spread; harness uses stdlib-only APIs compatible with 3.8+).

.github/workflows/refresh-data.yml refreshes the corpus index from AML daily at 11:00 UTC (07:00 EDT / 06:00 EST) and on manual workflow_dispatch. It runs the full pipeline (fetch-data → build-index → update-changelog → npm test) and commits the refreshed index back to main with the built-in GITHUB_TOKEN only when the corpus version actually advances — a no-op rebuild produces no commit. A commit with new law text also bumps the patch version and triggers an npm release (see Releases). The site structure is committed with it; a change to the structure alone (its first build, or a change to the structure code) is committed by itself, with no version bump and no release, since it is not in the package. Either commit also starts the website's deploy (see Deploy). Because npm test runs after the fetch and rebuild, the tests see that day's new data. A test must never assume what data/index/json/ says today: pin the values it depends on inside the test, or the refresh goes red on exactly the days law text changes and the new text never gets committed. The "Last index update" block below is stamped by that job.

Releases

.github/workflows/release.yml is the only workflow that publishes to npm. It runs the test suite, checks that the tag matches package.json, publishes with provenance, and creates a GitHub Release with generated notes. It starts in one of two ways.

Automatic patch releases (law text changed). When the daily refresh commits new law text, the same commit bumps the patch version (package.json, package-lock.json and server.json) and adds a dated "Automatic data release" entry to RELEASES.md naming which corpora moved. The job then pushes the vX.Y.Z tag and starts release.yml on it with gh workflow run (a tag pushed by the built-in token does not trigger workflows by itself; workflow_dispatch is GitHub's documented exception). Days with no new text produce no release. An automatic release ships main as it stands, so code merged since the last release goes out in the next one; bump the minor version by hand first if that code warrants it.

If the current version is not on npm yet (for example you bumped it by hand and have not tagged it), the refresh still commits data but does not bump past your version. If the release cannot be prepared (for example the npm registry is unreachable), the new law text is still committed without a version bump and the refresh run goes red. If an automatic release fails, its Release run goes red and every following refresh run goes red too, naming the run to rerun, until the version is published. To recover, fix the cause and rerun the failed Release run (Actions → Release → Re-run, or gh run rerun <id> --failed). Never re-tag or bump to recover.

Manual releases (code changes).

  1. In a pull request: bump the version in package.json, package-lock.json and server.json (both version fields), add a RELEASES.md entry headed ## vX.Y.Z — Unreleased, and, for a change a reader would notice, a WHATS-CHANGED.md entry headed ## Unreleased: Title, tagged MCP, whose MCP version line links to RELEASES.md with no anchor. release.yml refuses to publish if server.json differs from package.json. Once merged, the refresh keeps committing law text but does not release automatically until this version is on npm, so npm users get no new law text meanwhile. After the hand release has been on main for more than two days (New York dates), each refresh run goes red to say so.

  2. On release day, one commit on main, with the New York date (TZ=America/New_York date +%F):

    • ## Unreleased: Title becomes ## YYYY-MM-DD: Title in WHATS-CHANGED.md. The title must stay the same; the check rejects a changed one.

    • ## vX.Y.Z — Unreleased becomes ## vX.Y.Z — YYYY-MM-DD in RELEASES.md.

    • The entry's MCP version link gains the new RELEASES.md anchor. Compute it, never type it: python3 -c "import sys; sys.path.insert(0, 'scripts'); import whats_changed as w; print(w.github_slug('vX.Y.Z — YYYY-MM-DD'))" (for v0.5.0 — 2026-11-13 it prints v050--2026-11-13).

    • Check: node scripts/auto-release.js check-whats-changed --release must pass. It is the same gate release.yml runs before npm publish.

  3. Tag that commit and push: git tag vX.Y.Z && git push origin vX.Y.Z (the tag must match package.json, or the workflow fails).

Automatic data releases never get a WHATS-CHANGED.md entry and pass the gate. The refresh does not prepare one while WHATS-CHANGED.md has an Unreleased entry: in the normal flow that entry sits beside an unpublished hand bump, which already pauses automatic releases. If an Unreleased entry ever sits beside a version that is already on npm, the refresh commits the law text without a release and goes red, naming the fix, rather than ship the entry undated.

Authentication. release.yml is set up for npm trusted publishing (OIDC, no stored token). Until the trusted publisher is configured on npmjs.com it falls back to the NPM_TOKEN secret. One-time setup, by a package owner:

  1. On npmjs.com, open @betanyc/nyc-charter-laws-rules → Settings → Trusted Publisher → GitHub Actions.

  2. Fill in exactly (case-sensitive): Organization or user BetaNYC; Repository nyc-charter-laws-rules; Workflow filename release.yml (filename only, not the path); Environment name left blank. Under Allowed actions, also allow direct publishing with npm publish: configurations created after September 3, 2026 allow only npm stage publish by default, and the workflow publishes directly, so without this box npm rejects the trusted-publishing publish. Save. npm does not validate these fields when you save them.

  3. Set Settings → Publishing access → "Require two-factor authentication and disallow tokens". npm's docs say trusted publishers keep working under that setting, so the next release can only succeed through trusted publishing: a green Release run after this point is the confirmation, provided its "Publish to npm" step actually ran (release.yml skips that step when the version is already on npm, for example on a rerun). (A success before this step does not prove it, because the workflow falls back to NPM_TOKEN, and npm's docs give no way to tell from the run log which one was used.) If that release fails with an authentication error, the trusted publisher is misconfigured. Re-check step 2 and rerun it. If you re-allow tokens instead, repeat step 3 once trusted publishing is fixed.

  4. Once a release has succeeded with tokens disallowed, remove this repo's access to the NPM_TOKEN secret.

MCP Registry. After each successful release, .github/workflows/publish-mcp.yml lists that version in the official MCP Registry as io.github.BetaNYC/nyc-charter-laws-rules, from server.json, using GitHub OIDC (no secret). glama.json claims the server on Glama.

Package release history lives in RELEASES.md; CHANGELOG.md is machine-generated and tracks corpus data updates only. WHATS-CHANGED.md is the plain-language record of what a reader would notice.


This server is for research and informational purposes only. It does not provide legal advice.

Caveats are encoded at three levels so no response can be returned without one:

  1. Server instructions — the full disclaimer below is sent once as the server's instructions when a client connects, in every footer mode. Tool descriptions do not repeat it: it went out of them in issue #48, so it is not paid for on every turn. Some clients pass the instructions to the model and some do not, which is why level 2 never goes away.

  2. Response footer — every payload returned by the server ends with a disclaimer, regardless of which tool was called, what was found, or whether the call failed. By default the first response after the server starts carries the full footer below and every later response carries a one-line version (see NYC_CLR_FOOTER under Configuration).

  3. get_version instruction — the get_version tool description explicitly instructs the AI to call it before answering legal questions, so every response is grounded in the correct version of the law.

⚠️ This information is for research and informational purposes only and does not constitute legal advice. NYC laws and rules are amended frequently — always verify the current text at codelibrary.amlegal.com before acting on any information. For the latest rules information, see rules.cityofnewyork.us. For legal matters, consult a licensed attorney.

Official disclaimer from American Legal Publishing: The Codes and other documents that appear on this site may not yet reflect the most current legislation or rules adopted by the City. In addition, certain textual errors and omissions may temporarily exist, resulting from problems in the source database provided to American Legal and from which this website was created. Although these errors and omissions are being corrected, any user discovering any such error is invited to contact the publisher at NYC.editor@amlegal.com or 800-445-5588 and/or the NYC Law Department at NYCCodeRulesCharter@law.nyc.gov.

Built by BetaNYC. Feedback and improvements welcome — file a GitHub issue.

⚠️ Not legal advice. Verify at https://codelibrary.amlegal.com/codes/newyorkcity/latest/overview.


Repository structure

nyc-charter-laws-rules/
├── WHATS-CHANGED.md            ← what a reader would notice, newest first (ships in the package)
├── DATA-SOURCES.json           ← where the data comes from, for about_data (ships in the package)
├── data.json                   ← DCAT-US 3.0 catalog, generated from DATA-SOURCES.json
├── src/                        ← MCP server (TypeScript); betanyc-tools.ts is a shared copy
├── scripts/
│   ├── whats_changed.py        ← checks WHATS-CHANGED.md and DATA-SOURCES.json, writes data.json (shared copy; never edit here)
│   ├── tests/catalog_validate.py, mcp_shared/  ← CI validators for the two (shared copies)
│   ├── auto-release.js         ← automatic releases and the What's changed release gate
│   ├── fetch-data.js           ← downloads bulk XML ZIPs from AML
│   ├── build-index.js          ← thin CLI: reads ZIPs, writes JSON + Markdown indexes and the site structure
│   ├── build-site.js           ← thin CLI: builds the website into _site/ (scripts/lib/site/)
│   ├── serve-site.js           ← previews _site/ on 127.0.0.1
│   └── lib/
│       ├── extract-text.js     ← ordered-tree text-extraction helpers
│       ├── build-corpus.js     ← pure section builder (buildSectionsFromXml), unit-tested
│       ├── build-structure.js  ← site structure: subdivisions, links, chapter and title names
│       ├── render-section.js   ← renderSection: a section as ordered, typed blocks
│       ├── serialize-markdown.js ← the Markdown index, written from renderSection's blocks
│       └── site/               ← the website: data model, pages, HTML writer, sitemaps, New York clock
├── site/
│   ├── template/               ← unchanged copies of BetaNYC's Pages template files
│   └── assets/                 ← the site's own CSS and scripts (jump box, search, 404)
├── data/
│   ├── raw/                    ← downloaded ZIPs (gitignored — build locally)
│   ├── index/
│   │   ├── json/               ← committed: charter.json, admin_code.json, rules.json, versions.json
│   │   └── markdown/           ← committed: charter.md, admin_code.md, rules.md
│   └── structure/              ← site structure per document (committed by the daily refresh; not in the npm package)
├── _site/                      ← the built website (gitignored; npm run build-site)
└── dist/                       ← compiled MCP server (built locally)

The JSON and Markdown indexes are committed to the repo. Anyone who clones it gets every section of all three documents immediately — no build step required to browse or run the server.


Data source

All content is sourced from publicly available bulk XML downloads hosted by American Legal Publishing. No API key required. DATA-SOURCES.json describes each source (what BetaNYC changes, where to check a section, how to report an error), and the about_data tool answers from it.

Document

Sections

Current Through

Bulk XML source

NYC Charter

854

LL 2026/094, amendments through May 17, 2026

http://files.amlegal.com/pdffiles/NewYorkCity/Charter/XML.zip

NYC Administrative Code

12,558

LL 2026/094, amendments through May 17, 2026

http://files.amlegal.com/pdffiles/NewYorkCity/Admin/XML.zip

Rules of the City of New York

8,645

Rules effective through May 20, 2026

http://files.amlegal.com/pdffiles/NewYorkCity/Rules/XML.zip

AML publishes updated ZIPs as new local laws and rules are adopted. Re-run npm run fetch-data && npm run build-index to refresh the index and commit the updated files.

Site structure (data/structure/)

The index's text is flat. Its subdivisions run together, and its cross-references are plain words. build-index also writes data/structure/<corpus>.json for the website (epic #68), from the same XML in the same run. The MCP server does not read it, and it is not in the npm package.

BetaNYC builds this file from American Legal Publishing's bulk XML. The anchors, link targets and titles taken from the publisher's chapter key are worked out by BetaNYC and can be wrong. It is not an official record.

Per section, in index order:

  • parents: the Title, Chapter, Subchapter, Article and so on that the section sits in, outermost first, each named in groups with its heading. A chapter file that has no Title record around it (the publisher puts a Title's record only in its first chapter's file) takes its title from the publisher's anchor name for the chapter (T03C007 is Title 3, Chapter 7). When nothing matches, the chapter has no title rather than a guessed one; titleStats counts each case.

  • blocks: the paragraphs of text, each a start/end slice of it. A subdivision has its label as printed (a., (1)), its depth (the publisher's indentation) and an anchor built from its labels ((b)(1)), with -2 added when the law repeats a label in one section. Editor's notes are note blocks.

  • links: each cross-reference as a start/end slice of text and its target, one of:

    • a section: corpus, the publisher's name for the target, its id, and anchor when it points into a subdivision;

    • a Title or Chapter heading that is not a section: corpus, name, id and group: true;

    • a web address: kind: "web" and url;

    • an attached file: kind: "file" and file;

    • or, when the target is not found, corpus and name with resolved: false. When the publisher put the target's anchor id or name on more than one record, the link is not pointed at either: it also has ambiguous: true. linkStats counts these.

Known limits. Depth is the publisher's indentation. In the July 2026 build, 13 sections have labels with no indentation, and in 3 of them (Rules § 5000-02, § 5-08 and § 113-07) letters and numbers sit at one depth, so they get anchors like (1) and (1)-2 instead of (c)(1). History lines ("(Am. L.L. ...)") are ordinary text blocks, because the XML does not mark them.

The text is not repeated. Every offset points into text in data/index/json/<corpus>.json, and the file records that file's sha256 (indexSha256, the same as versions.json). A structure file built from other text fails test/structure.test.js. scripts/lib/render-section.js turns a section and its entry into blocks; the Markdown index is written from them, with the body joined back into one paragraph, so its bytes do not change.

The website (BetaNYC Law Reader)

npm run build-site builds a static website from the index and its structure: the BetaNYC Law Reader, which will live at law.beta.nyc (epic #68). It builds the Charter only for now. The build fetches nothing, and .github/workflows/deploy-site.yml publishes it (see Deploy).

What it builds, into _site/ (git-ignored, never committed):

  • Pages: a home page, the Charter's contents, one page per chapter, one page per section at a path from its citation (/charter/sections/259), a search page, an About page and a 404 page. Two sections that share a number (§ 20-t, § 530 and § 808) each get the number plus American Legal's id (/charter/sections/530-0-0-0-6575), and the plain path lists both.

  • On each section page: breadcrumbs, previous and next links, a side list of every Charter chapter with the section's own chapter open to its sections under a "Charter chapters" heading (on a wide screen it scrolls on its own to the section's link, and a focused link never hides under the heading; on a phone it folds behind one closed "Charter chapters" button above the breadcrumbs, and with JavaScript off behind a closed "Charter chapters" fold, so the law text still starts near the top; the skip link jumps past it; chapter and shared-number pages get the same list), each subdivision indented with its own link (#(b)(1)), references to other Charter sections as links (references into the Administrative Code and the Rules stay plain text until those books are on the site; links the structure marks unresolved or ambiguous stay plain text too), and the source: American Legal Publishing, a link to the section's own page there (https://codelibrary.amlegal.com/codes/newyorkcity/latest/NYCcharter/<id>; a chapter page links to the chapter's), and "BetaNYC modified this." Law pages leave the footer's "The text comes from American Legal Publishing, and BetaNYC modified it" sentence off, since the source box says it; every other page keeps it.

  • At the bottom of every page but About, in plain HTML: "American Legal Publishing's text is current through …" (the publisher's line from versions.json), "BetaNYC's copy last changed on …" (indexedAt, in New York time; the index keeps no date for when the publisher's files were last checked), the bold line "This is BetaNYC's copy, for research. It is not the official text and not legal advice. The official Charter is at American Legal Publishing.", and a link to the full disclaimer on the About page. The About page (modeled on BetaNYC's Grounding AI with NY Open Data site) says why the site exists, how the law got online (BetaNYC's 2014 testimony in support of Intro 149, which became Local Law 37 of 2014, Administrative Code § 7-111), what BetaNYC changed, how current it is, who built it, how BetaNYC uses AI, the licenses, how to report a mistake (lab@beta.nyc or a GitHub issue) and how to support BetaNYC. It has no warning at the top and no bottom box; it ends with the Disclaimer section, which opens with the same bold line and then shows the full disclaimer, read from FOOTER in src/tools.ts when the site is built, so the site and the MCP server say the same thing, and says that the paragraph starting "Official disclaimer from American Legal Publishing" is the publisher's, written for its own site. Its last line, "Built by BetaNYC...", is left out, since the page footer says it; if FOOTER stops ending with that line, the build stops.

  • Search: one box, on the home page and the search page; every other page reaches it through the top bar's Search link. Its hint (Try "§ 259", "259", or "budget office") is placeholder text inside the box. A citation (§ 259, 259, charter 259, 259(a), chapter 11) goes straight to its page, from citations.json; a number two sections share shows both. Words are searched with Pagefind, a static index the browser loads in pieces, with results by book, citation, heading and a highlighted snippet, links to the matching subdivisions, filters and paging. Without JavaScript, the box is replaced by a link to the contents.

  • Data files: redirects.json (American Legal ids to our paths; the 404 page uses it, so /charter/0-0-0-1263 lands on § 259), index.json (the contents as one tree), metadata.json (build time in New York time, this repo's commit, each book's index sha256), citations.json, a sitemap per book under sitemap.xml, and robots.txt, which welcomes search engines, AI answer engines and AI training crawlers.

  • Search engines and AI assistants: each page's title starts with its citation (NYC Charter § 259: Independent budget office | BetaNYC Law Reader), with a description of at most 160 characters from the law's own words, a canonical link on https://law.beta.nyc (SITE_BASE in scripts/lib/site/config.js), and Legislation and BreadcrumbList structured data that uses only properties schema.org defines. The search page is noindex.

The frame (top bar, footer, colors, type) is BetaNYC's Pages template: site/template/ holds unchanged copies of its site.css, nav.js and logos, and site/template/README.md says which commit and how to update them. The breadcrumbs, the side list of chapters, the search box, buttons, filters, paging and the back-to-top button are parts from the New York State Design System (@nysds/components), colored from the template's variables in site/assets/law.css, which names no colors itself. The site does not use NYSDS's global header or footer, or the parts NYSDS reserves for official State sites. The section text, the side list and the bottom box are plain HTML, and the law text uses the template's body font, so they read with JavaScript off, in a screen reader and in print. License notices for NYSDS (CC0, with Material Icons under Apache 2.0 and Lit under BSD 3-Clause) and Pagefind (MIT) ship with the site in licenses/; DOMPurify's notice, which NYSDS includes, is in assets/nysds/nysds.js.

The site's layout follows the DC Council's code site, code.dccouncil.gov. No DC code is used.

AI agents use the page too. Every control has a name, and no two share one; npm run test:site checks that in the browser's accessibility tree. The site does not offer WebMCP tools yet: those come in Phase 4a (#70). AI assistants that want the law directly should use this repo's MCP server.

Build and look at it locally:

npm run build-index          # writes data/structure/ (or use the copy the daily refresh commits)
npm run build-site           # writes _site/; --no-search skips the Pagefind index
npm run serve-site           # http://127.0.0.1:8080/, served the way GitHub Pages serves it

build-site takes --index-dir, --structure-dir and --out to build from other copies of the data. It stops with a message if data/structure/ is missing or was built from other text than the index, or if versions.json disagrees with the index's count. It only ever clears a folder it made itself.

Measured on 2026-11-22 on a Mac (Apple silicon), from the July 2026 Charter (854 records), in decimal megabytes: 862 pages, 15.0 MB on disk (11.2 MB of law pages, 3.3 MB gzipped; 2.4 MB of Pagefind index; 1.1 MB of shared files, mostly NYSDS), built in about 0.5 seconds, Pagefind included. GitHub Pages allows a 1 GB site and a 10-minute deployment. Projected to all three books (about 22,200 pages), from each book's text size and the length of its chapters' contents lists: about 390 MB and about 15 seconds to build. The deployment time for that many files (about 45,000, with Pagefind's pieces) has not been measured.

Deploy

.github/workflows/deploy-site.yml builds the site and publishes it to GitHub Pages at law.beta.nyc. It runs:

  • on a push to main that changes the site's code or what it reads: data/index/, data/structure/, scripts/build-site.js, scripts/lib/site/, scripts/lib/render-section.js, site/, src/tools.ts (the disclaimer), DATA-SOURCES.json, package.json, the lockfile, or the workflow itself;

  • after the daily refresh, only when it committed new law text or a new site structure. The refresh pushes with the built-in GITHUB_TOKEN, and GitHub does not start other workflows from that push, so its last step starts this one with gh workflow run (GitHub's docs). No commit, no deploy;

  • by hand: the Actions tab, Deploy Site, Run workflow on main, or gh workflow run deploy-site.yml --ref main.

Each run installs with npm ci, runs npm test, and builds the whole site fresh with npm run build-site. The build stops the run, before anything is deployed, if data/structure/ is missing or was built from other text than the index. Nothing is committed: the HTML goes from _site/ straight to Pages with GitHub's own actions (configure-pages, upload-pages-artifact, deploy-pages). Only main deploys, one run at a time. After the deploy, the run checks that the home page and /about answer 200; if they do not, the run goes red, but the deployment stays up. The custom domain is set in the repository's Pages settings, so the site needs no CNAME file.


Prerequisites

  • Node.js 20 or later (tested on 20.x and 22.x)


Installation

npx @betanyc/nyc-charter-laws-rules

The corpus data is bundled in the package — no setup required.

Global install

npm install -g @betanyc/nyc-charter-laws-rules
nyc-charter-laws-rules

From source (for development or refreshing the index)

git clone https://github.com/BetaNYC/nyc-charter-laws-rules.git
cd nyc-charter-laws-rules
npm install

Claude Desktop configuration

Add to your claude_desktop_config.json:

{
  "mcpServers": {
    "nyc-charter-laws-rules": {
      "command": "npx",
      "args": ["-y", "@betanyc/nyc-charter-laws-rules"]
    }
  }
}

Or if installed globally:

{
  "mcpServers": {
    "nyc-charter-laws-rules": {
      "command": "nyc-charter-laws-rules"
    }
  }
}

Setup

The index is already committed — no data download needed to run the server.

Step 1 — Build and start the server (from source only):

npm run build
npm start

That's it. The committed JSON index is loaded automatically.

Refreshing the index from AML

Run this when AML publishes a new version of the Charter, Admin Code, or Rules:

npm run fetch-data    # downloads ~50MB of bulk XML ZIPs into data/raw/
npm run build-index   # parses XML, writes data/index/json/, data/index/markdown/ and data/structure/

fetch-data sends a User-Agent naming this package and version, gives each download 120 seconds (they are several megabytes each), and retries a 429 or 5xx answer up to twice, honoring Retry-After (scripts/lib/fetch-retry.js). If any of the three downloads fails, it stops with an error, so no index is built with a document missing.

Then commit the updated index files and push. The get_version tool will reflect the new currency dates after the next server restart.

Placing ZIP files manually

If you prefer to download the ZIPs yourself rather than using npm run fetch-data, place them in data/raw/ with these exact filenames before running npm run build-index:

data/raw/charter.zip       ← http://files.amlegal.com/pdffiles/NewYorkCity/Charter/XML.zip
data/raw/admin_code.zip    ← http://files.amlegal.com/pdffiles/NewYorkCity/Admin/XML.zip
data/raw/rules.zip         ← http://files.amlegal.com/pdffiles/NewYorkCity/Rules/XML.zip

The data/raw/ directory is gitignored — the ZIPs will not be committed.


Configuration

Claude Code

Add to your project's .mcp.json or .claude/settings.json:

{
  "mcpServers": {
    "nyc-charter-laws-rules": {
      "command": "npx",
      "args": ["-y", "@betanyc/nyc-charter-laws-rules"]
    }
  }
}

Or if running from a local clone:

{
  "mcpServers": {
    "nyc-charter-laws-rules": {
      "command": "node",
      "args": ["/path/to/nyc-charter-laws-rules/dist/index.js"]
    }
  }
}

Getting current law text (NYC_LAWS_INDEX_DIR)

The Refresh Data workflow commits a refreshed index to main every morning when AML has published new text. To serve that text while running the pinned npm package, keep a sparse clone of just the index and point the server at it:

git clone --filter=blob:none --sparse https://github.com/BetaNYC/nyc-charter-laws-rules.git
cd nyc-charter-laws-rules
git sparse-checkout set data/index/json
# later, to update:
git pull
{
  "mcpServers": {
    "nyc-charter-laws-rules": {
      "command": "npx",
      "args": ["-y", "@betanyc/nyc-charter-laws-rules"],
      "env": {
        "NYC_LAWS_INDEX_DIR": "/path/to/nyc-charter-laws-rules/data/index/json"
      }
    }
  }
}
  • The directory must hold versions.json, charter.json, admin_code.json, and rules.json, laid out like data/index/json/. A leading ~/ expands to your home directory. Any other relative path resolves against the server process's working directory, which your MCP client chooses, so an absolute path is safest.

  • If the variable is set and versions.json is not there, the server refuses to start and says why. It never falls back to the bundled index silently. Unset or blank means the bundled index.

  • The server notes the directory it is serving on stderr at startup. Restart it after a git pull; the index is read once per process.

  • get_version reports the currency dates of whichever index is loaded.

Every tool response ends with a disclaimer. NYC_CLR_FOOTER sets how much of it:

Value

Behavior

full-then-compact (default)

The full footer on the first response after the server starts, then the one-line footer on every response after.

full

The full footer on every response, as through 0.3.x.

  • "First response" means the first since this server process started. MCP does not tell a server when a new chat begins, so a client that keeps the server running across chats sends the full footer only once. The full text also goes out as the server's instructions on every connection, in both modes.

  • Unset or blank means the default. Any other value means full (more disclaimer, never less), and the server prints a warning naming the variable to stderr at startup.

"env": { "NYC_CLR_FOOTER": "full" }

Common workflows

Look up a specific section of the Charter

1. get_version()                          → confirm how current the law is
2. get_section("§ 259")                   → retrieve the section text

Find everything the Admin Code says about a topic

1. search("sidewalk shed", corpus="admin_code", limit=20)
2. get_section("§ 28-3310.1")            → pull a specific result

Browse the Rules on a subject area

1. list_titles("rules")                   → find the relevant chapter by its heading
2. get_title("rules", "Chapter 900")      → its sections (Fire Protection Systems)
3. search("fire safety", corpus="rules")  → keyword search within rules
1. get_version()                          → note the effective date for each corpus
2. search("open meetings", corpus="all")  → find relevant sections
3. get_section("§ 1-207")                → retrieve full text

Changelog

The complete, dated record of every index rebuild lives in CHANGELOG.md. Each entry records which corpus version was current at the time of the build and flags whenever a corpus's currentThrough version advanced.

The block below is stamped automatically with the most recent rebuild every time npm run update-changelog runs — see CHANGELOG.md for the full history.

Last index update: 2026-11-22 — ⬆️ Updated

Corpus

Current through

Sections

NYC Charter

Current through Local Law 2026/165, enacted November 19, 2026,

856

NYC Administrative Code

Current through Local Law 2026/165, enacted November 19, 2026,

12,655

Rules of the City of New York

Current through rules effective November 14, 2026.

8,733

Release history

Package version history (distinct from the per-rebuild record in CHANGELOG.md):

  • 0.1.2 — May 25, 2026: Charter and Admin Code current through LL 2026/094 (enacted May 16, 2026), up from LL 2026/086; Rules through May 20, 2026, up from May 15; Admin Code 12,551 → 12,558 sections.

  • 0.1.1: Initial published release with full JSON and Markdown indexes committed to repo.

  • 0.1.0: Initial release.

About BetaNYC

This project is built and maintained by BetaNYC, New York's civic technology and open-data community. We work to improve lives in New York through civic design, technology, data, and public-interest technology.

Come do civic tech with us. We run public events, meetups, and hands-on data classes throughout the year — including NYC School of Data and CityCamp NYC, and we host frequent civic-tech gatherings. See what's coming up on our events calendar.

Sustain this work. These MCP servers are free and open source. To help keep this work going and find BetaNYC's tools, please consider donating and becoming a Beta Builder.

Building on this? Tell us!

If you build something with this project, we'd love to hear about it. We can help other New Yorkers find it. BetaNYC publishes a weekly newsletter, This Week in NYC's Civic Technology and Open Data.

BetaNYC maintains a suite of open-source MCP servers for NYC and NYS civic data. See the full directory, with install details for each, at beta.nyc/ai-tools.

This server pairs directly with:

  • nyc-council-mcp: see the Council legislation, sponsors, votes, and hearings that create and amend the Code.


Contributing

Issues and pull requests welcome at github.com/BetaNYC/nyc-charter-laws-rules.


Support our work

Freedom isn't free. Support BetaNYC.

License

MIT License

Copyright (c) 2026 BetaNYC

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Available Tools

8 tools
about_betanycAbout BetaNYC and this serverA
Read-only

Who built this server and how to reach them: BetaNYC, a project of the Fund for the City of New York. Returns what BetaNYC is, links to its events, newsletter and donation page, where to report a bug in this server or ask for a new feature (this server's GitHub issues), and this server's name and version.

Inputs: no named parameters. Returns: about, links, server, history, +4 more

about_dataWhere this server's data comes fromA
Read-only

Where this server's data comes from and how far to trust it. For each kind of data: who publishes it and a link, whether it is an official record (only data its publisher published and BetaNYC did not modify is; data BetaNYC modified or produced is not), how it was gathered, what BetaNYC did to it (for example cleaned it, matched it to addresses, joined it with other data, or counted it), how current it is on this server, what it covers and what is missing, the terms of use and the credit line to print, where to check a figure at the official record, where to report an error (to BetaNYC when BetaNYC modified or produced the data, to the publisher for the original records, and to this server's issues for a bug), which tools use it, and corrections that touched it. Call it whenever someone asks where an answer comes from, how current or accurate it is, or how to check or cite it. topic narrows it to one kind of data, or to the data behind one tool (give the tool's name). For who built this server, use about_betanyc. Topics on this server: charter, admin-code, rules.

Inputs: topic. Returns: note, topic, server, topics, +6 more

get_sectionGet a sectionA
Read-only

Retrieve a specific section by its citation (e.g. '§ 259', 'Section 259', '11-602.1', 'Chapter 11'). Input is normalized (with or without '§', any case). Pass 'corpus' to disambiguate when the same citation exists in multiple documents (e.g. charter 'Chapter 3' vs a rules chapter); if multiple sections still match, a disambiguation list is returned.

Inputs: citation (required), corpus.

get_titleGet a chapter or titleA
Read-only

List a chapter's sections in order: its heading, then each section's citation and heading (get_section gives the text). 'Chapter 70' gives every chapter with that number. Administrative Code only: 'Title 24' gives the chapters whose sections are numbered 24-… (a lettered title such as 16-A shares its parent's numbers), and 'Title 3, Chapter 1' narrows to those numbered 1. Numbers match whole: 'Chapter 1' is not 'Chapter 10' or 'Chapter 1-A'.

Inputs: title (required), corpus (required), limit, offset.

get_versionHow current the text isA
Read-only

Return the currency date for each document — how current the Charter, Administrative Code, and Rules are. Each corpus updates on its own schedule. Always call this tool before answering legal questions so responses are grounded in the correct version of the law.

Inputs: no named parameters.

list_titlesList chapters or titlesA
Read-only

List a document's chapters in order, each with its heading. Administrative Code chapters show their section range, since several share a number: 'Chapter 1 (§ 3-101 to § 3-196)'. Rules chapters can share a number too (the index does not record Rules titles); their headings tell them apart.

Inputs: corpus (required), limit, offset.

whats_changedWhat's changedA
Read-only

What has changed in this server, its data and its website, newest first, from the project's WHATS-CHANGED.md: new tools and pages, new data, data fixes, and corrections when BetaNYC published something wrong. Each correction says what to re-check if you used the old numbers. Call this before relying on a figure you got from this server earlier, or when a user asks whether something was fixed. Filter with since (YYYY-MM-DD; also keeps older entries that have an update on or after that date) and tag (Site, Data, MCP or Correction).

Inputs: tag, limit, since. Returns: note, server, source, entries, +4 more

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.1/5.0

    Scored across 8 tools

    Disambiguation4/5

    The four retrieval tools are well separated by intent: search is keyword matching, get_section is citation lookup, list_titles lists chapters of a document, and get_title lists sections within a chapter. The descriptions explicitly call out the tricky boundaries (search vs. get_section, and the 'Chapter 3' ambiguity in get_section). Minor residual overlap between search and get_section, and the three meta tools (get_version, about_data, about_betanyc) are close cousins but still distinguishable.

    Naming Consistency3/5

    The core navigation tools follow a clean get_/list_ verb_noun pattern (get_section, get_title, get_version, list_titles), but the set mixes in a bare verb (search), a noun-phrase pair (about_data, about_betanyc), and a different shape entirely (whats_changed). Readable and mostly predictable, but three conventions coexist rather than one.

    Tool Count5/5

    Eight tools is well matched to a legal-corpus server: four for retrieval/navigation and four for versioning, provenance, and change history. Each tool earns its place with no filler.

    Completeness4/5

    The surface covers the full research loop: search, citation lookup, hierarchical browsing (chapters → sections), currency, provenance, and changelog. Minor gaps: no tool to list available documents/corpora explicitly (only inferred from arguments), no full-text chapter dump, and no cross-reference or definition lookup.

    Maintenance

    ActivityActive
    ResponsivenessUsually handled

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      C
      maintenance
      Enables AI assistants to retrieve, search, and track changes to US Code of Federal Regulations sections via the eCFR API, returning actual regulation text with citations and point-in-time date support.
      7
      33 PyPI
      1
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables AI agents to retrieve the full text of annotated statutory sections by citation, search the statutes by topic or keyword, and list all published titles, returning chapter, amendment history, and case-note annotations. Keyless access with citation-to-URL resolution handled internally, including ambiguous citation candidates.
      51 npm
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      Lets AI assistants search and retrieve New York State legislative records — bills, laws, members, committees, floor calendars, agendas, transcripts, votes, and change feeds — through the NYS Open Legislation API or an optional local SQLite corpus. It supports full-text ElasticSearch queries and returns citation-ready links for law sections.
      357 npm
      5
      MIT