lastfm-mcp
AGENTS.md55 starsChanged 10 months agoMITView on GitHub
Guidance for coding agents (Claude Code, Codex) working in this repository. Cloudflare Worker implementing a Model Context Protocol (MCP) server that connects AI assistants to Last.fm listening data. Runs on workerd with a Rate Limiting binding (REGISTRATION_RATE_LIMITER) and three KV namespaces: OAUTH_KV (OAuth clients, grants and tokens), MCP_SESSIONS (the Last.fm response cache; the name predates OAuth) and MCP_RL (per-IP rate limits). The TOOL_EVENTS Analytics Engine binding receives one anonymous data point per tool call (its layout, including double2 for the…
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.
Of the AGENTS.md files we read, the 35,117 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository4 other files it gives its agents.
- building-mcp-server-on-cloudflareSkill
- cloudflareSkill
- workers-best-practicesSkill
- wranglerSkill
The file
We split this AGENTS.md into the rules it gives an agent
6 rules. About 0 are common, 3 are distinctive, and 3 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈3
Distinctive · estimate
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 34
After it merges, tag that merge commit and create the GitHub release.
- Very specific: line 40
Test runner: vitest 4 with @cloudflare/vitest-pool-workers 0.22 (runs in workerd/miniflare).
- Very specific: line 102
Use import type for type-only imports
- Distinctive: line 103
No file extensions on relative imports (Wrangler bundles them)
- Distinctive: line 105
No path aliases — all relative paths
- Very specific: line 138
Always use error instanceof Error ?
≈ “Common” is an estimate: at least 1 in 5 of the 45,344 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
AGENTS.md
Guidance for coding agents (Claude Code, Codex) working in this repository.
Cloudflare Worker implementing a Model Context Protocol (MCP) server that connects AI assistants to Last.fm listening data. Runs on workerd with a Rate Limiting binding (REGISTRATION_RATE_LIMITER) and three KV namespaces: OAUTH_KV (OAuth clients, grants and tokens), MCP_SESSIONS (the Last.fm response cache; the name predates OAuth) and MCP_RL (per-IP rate limits). The TOOL_EVENTS Analytics Engine binding receives one anonymous data point per tool call (its layout, including double2 for the Last.fm HTTP requests the call made, is in src/analytics/toolEvents.ts), in the lastfm_mcp_tool_events_staging dataset on staging and lastfm_mcp_tool_events in production.
Build / Test / Lint Commands
npm run dev # Local dev server (wrangler dev, port 8787)
npm run build # Dry-run deploy to validate build (wrangler deploy --dry-run)
npm run deploy # Deploy to staging (the default `lastfm-mcp` Worker)
npm run deploy:prod # Deploy to production (`lastfm-mcp-prod`); CI normally does this, see below
npm run setup:prod # Create production KV namespaces and set the three secrets
npm run lint # ESLint (src and dashboard/src)
npm run format # Prettier --write
npm run format:check # Prettier --check (CI)
npm run test:multi-user # Manual multi-user check against a running server (scripts/test-multi-user.js)
npm run render:share # Re-render og.png, apple-touch-icon.png and .github/assets/github-preview.png from src/pages/share/*.html (macOS: headless Chrome + sips; needs Google Fonts)
npm run render:readme # Re-write .github/assets/wave.svg, the README banner, from src/pages/share/wave.js (Node only)
npm run cf-typegen # Regenerate Worker type bindings (run after changing wrangler.toml; produces worker-configuration.d.ts — generated, do not edit by hand)
npm run test:dashboard # Dashboard Worker tests (dashboard/vitest.config.mts)
npm run dashboard:dev # Dashboard Worker local dev server (every page request gets a 403 without an Access JWT)
npm run dashboard:deploy # Deploy the dashboard Worker by hand; CI never doesDeploys and Releases
A merge to main is a production deploy. CI (.github/workflows/ci.yml) lints, tests and builds every PR and push, then runs npm run deploy:prod on each push to main. Test risky auth changes on staging (npm run deploy) before merging.
To release:
- In one PR, bump
versioninpackage.json,package-lock.jsonandserver.json, andSERVER_VERSIONinsrc/mcp/protocol.ts.server_info, the server card and/healthreportSERVER_VERSION;test/server-json.test.tsfails ifserver.jsondrifts from it. In the same PR, updateLATEST_RELEASEinsrc/pages/landing.ts(the version and a one-line blurb for the landing page's "In x.y.z" line, which links to the GitHub release) andLANDING_PAGE_UPDATED;test/pages/landing.test.tsfails if its version drifts fromSERVER_VERSION. - After it merges, tag that merge commit and create the GitHub release.
- Publish the new version to the official MCP Registry as
com.lastfm-mcp/lastfm:MCP_PRIVATE_KEY=<hex> mcp-publisher login dns --domain lastfm-mcp.com, thenmcp-publisher publish. The key proves control of the domain through the apexv=MCPv1TXT record; it's kept outside the repo. A published version can't be changed, so a listing-only fix publishes a prerelease such as2.8.0-1. - The release name and body follow Rian's side-project release notes contract (
~/git/product-ai/05-personal/side-projects/release-notes-contract.md):lastfm-mcp vX.Y.Z — <tagline>, then an opening paragraph before its## What's new/## Fixes/## Under the hoodsections. A release stays on GitHub unless Rian explicitly asks for an elezea.com cross-post. Only then, put<!-- post-to-elezea -->on its own line at the end of the body:.github/workflows/elezea-release-post.ymlposts a release that carries the marker to elezea.com, and the endpoint rejects anything off-contract. Adding the marker after publishing does nothing, because the workflow runs only when a release is published. A release runs the workflow from its tagged commit, so tag a commit that includes this version of the workflow.
Running Tests
Test runner: vitest 4 with @cloudflare/vitest-pool-workers 0.22 (runs in workerd/miniflare). Requires Node 22 (see .nvmrc); the config uses the cloudflareTest() plugin shape, not the removed defineWorkersConfig.
wrangler is pinned to the exact version @cloudflare/vitest-pool-workers depends on, so tests, npm run dev, and deploys share one wrangler and one workerd. A caret range resolves to the newest wrangler and splits the tree in two again. When bumping vitest-pool-workers, move the pin in the same change:
npm view @cloudflare/vitest-pool-workers@<new-version> dependencies.wrangler # the version to pin
npm ls wrangler workerd # after install: one copy of eachnpm test # All tests
npx vitest run # All tests, exit when done
npx vitest run test/utils/retry.test.ts # Single file
npx vitest run -t "should succeed" # Single test by name (matches against full describe → it path)
npx vitest run test/protocol/ # All tests in a directoryCode Style
Formatting (Prettier)
- Tabs for indentation (not spaces)
- No semicolons
- Single quotes
- 140-char print width
- LF line endings
Linting (ESLint)
@typescript-eslint/no-unused-vars: error — prefix unused params/vars with_@typescript-eslint/no-explicit-any: warn — avoid but not blocked- TypeScript strict mode is enabled
File Headers
Every file (source and test) must have exactly two // ABOUTME: comment lines at the top. Line 1 describes WHAT the file is. Line 2 describes its PURPOSE or SCOPE.
// ABOUTME: Smart caching utility with TTL-based expiration for Last.fm API responses.
// ABOUTME: Provides optimized cache TTLs per endpoint type and request deduplication.The same two // ABOUTME: lines open .js and .mjs files too (src/pages/share/wave.js, scripts/*.mjs). Exceptions:
src/pages/landing.htmland thesrc/pages/share/*.htmlsources put both lines in one HTML comment right after<!doctype html>.src/pages/llms.mdhas none: its first lines are served as-is at/llms.txt, so agents read them.- The one-line module fixtures (
test/fixtures/text-module.html,text-module.md) and binary files have none.
Imports
- External/third-party packages first
- Blank line
- Relative project imports
import { McpServer } from '@modelcontextprotocol/server'
import { z } from 'zod'
import type { Env } from '../types/env'
import { toolError } from './error-handler'- Use
import typefor type-only imports - No file extensions on relative imports (Wrangler bundles them)
- MCP SDK v2: server code imports from
@modelcontextprotocol/server, tests use@modelcontextprotocol/client; the handler comes fromagents/mcp/server - No path aliases — all relative paths
Naming Conventions
| Thing | Convention | Example |
| Files (source) | camelCase or kebab-case | cachedLastfm.ts, oauth-handler.ts |
| Files (test) | Match source + .test.ts | retry.test.ts, index-oauth.test.ts |
| Directories | lowercase | auth/, mcp/, utils/ |
| Functions | camelCase | createMcpServer, fetchWithRetry |
| Classes | PascalCase | LastfmClient, SmartCache |
| Interfaces/Types | PascalCase, no prefix | Env, SessionPayload (not IEnv) |
| Enums | PascalCase + PascalCase members | ErrorCode.ParseError |
| Constants | UPPER_SNAKE_CASE | SERVER_VERSION, PROTOCOL_VERSION |
| Variables | camelCase | sessionId, cachedClient |
Type Patterns
- Interfaces for data shapes, not classes
- Union types for constrained values:
type Period = '7day' | '1month' | ... - Zod schemas for MCP tool input validation
- Domain types co-located with their client (e.g.,
LastfmTrackinsrc/clients/lastfm.ts) - Shared protocol types in
src/types/ - Type guards for runtime validation (e.g.,
isJSONRPCRequest())
Error Handling
Three patterns used at different layers:
- HTTP handlers — try/catch, log with
console.error, returnResponsewith status code - MCP tools — try/catch, return
toolError('tool_name', error)fromsrc/mcp/tools/error-handler.ts - Non-critical systems — fail open (e.g., rate limiter returns
{ allowed: true }if KV is down)
Always use error instanceof Error ? error.message : 'Unknown error' when stringifying caught errors.
Test Conventions
Tests live in test/ mirroring the src/ structure. Use describe/it (not test).
import { describe, it, expect, vi, beforeEach } from 'vitest'
describe('Feature', () => {
beforeEach(() => {
vi.clearAllMocks()
})
describe('subfeature', () => {
it('should do the expected thing', async () => {
expect(result).toBe(expected)
})
})
})- Mock with
vi.fn(),.mockResolvedValue(),.mockRejectedValue() - Mock fetch:
globalThis.fetch = vi.fn() - Timer control:
vi.useFakeTimers()/vi.useRealTimers()/vi.advanceTimersByTimeAsync() - Worker integration tests use
import { env, createExecutionContext, waitOnExecutionContext } from 'cloudflare:test' - OAuth flow helpers live in
test/helpers/(oauth-flow.ts,cimd-fetch.ts); captured 0.10.3 KV records for the upgrade-survival test are intest/fixtures/
Architecture Overview
src/
index-oauth.ts # Sole Worker entry point: static routes, per-IP rate limits, per-origin OAuth provider
pages/ # Landing page (/) and /llms.txt, built from .html/.md sources imported as text modules
landing.html # Page source with {{ORIGIN}} placeholders and FAQ/STRUCTURED DATA markers
landing.ts # buildLandingPage(origin) fills the markers and origin; LANDING_PAGE_UPDATED drives sitemap lastmod
faq.ts # FAQ items, rendered into the page and into FAQPage JSON-LD from one list
llms.md # /llms.txt source: setup steps for agents, with {{ORIGIN}} and {{TOOLS}}
llms-txt.ts # buildLlmsTxt(origin) fills llms.md, generating the tool list from the tool catalogs
template.ts # fillPlaceholders(): fills {{UPPER_SNAKE}} tokens and throws on any left unfilled
share/ # og.png and apple-touch-icon.png (served at /og.png, /apple-touch-icon.png), their HTML sources, and the GitHub preview's source
analytics/ # Anonymous tool-call events for TOOL_EVENTS: data point layout, client labels, the waitUntil writer
auth/ # OAuth handler (consent, Last.fm sign-in, callback), consent page, /mcp resource rewrite
clients/ # Last.fm API client + caching decorator
mcp/ # MCP SDK server, tools (public + authenticated), prompts, resources
recommendations/ # get_music_recommendations: pure scoring, the engine (cached candidates, starters, partial results), output formatting
types/ # Shared types: Env
utils/ # Cache, rate limiting, retry, per-call Last.fm request policy, https redirect, security, date formatting, mood mapping, breadcrumbsSingle Worker entry point configured in wrangler.toml: main = "src/index-oauth.ts". The [env.production] block points to the same entry — it only renames the deployed Worker.
Two [[rules]] in wrangler.toml bundle non-code files: Text imports **/*.html and **/*.md as strings, and Data imports **/*.png as ArrayBuffers. Their module types are declared in src/types/text-modules.d.ts. Addresses a visitor copies use {{ORIGIN}}, so staging and localhost show their own URL; canonical, Open Graph, JSON-LD and FAQ URLs stay hardcoded to https://lastfm-mcp.com. When the landing page changes, update LANDING_PAGE_UPDATED in src/pages/landing.ts.
The share images are committed PNGs. After editing src/pages/share/og-card.html, icon.html, github-preview.html or wave.js (the wave drawing all three pages load), run npm run render:share on macOS and commit the PNGs with the change. The HTML and wave.js are never bundled or served. render:share re-encodes every PNG, so restore any whose source didn't change rather than committing new bytes for the same picture.
The README's art lives in .github/assets/. wave.svg is the banner, written by npm run render:readme from wave.js, so run it whenever wave.js changes. github-preview.png is the 1280×640 GitHub social preview; GitHub has no API for it, so after re-rendering it upload it by hand under Settings → General → Social preview.
Every MCP request needs an OAuth bearer token: unauthenticated POST /mcp returns 401 with WWW-Authenticate, which starts the client's sign-in. OAuth is the only sign-in path: the manual /login → ?session_id= flow was removed in #34, so Last.fm session keys are only stored inside encrypted grant props. The "public" tools in src/mcp/tools/public.ts are the ones that don't need the user's Last.fm session, not tools reachable without sign-in. src/auth/jwt.ts is no longer imported by any source file.
Key dependencies: @modelcontextprotocol/server (MCP SDK v2), @cloudflare/workers-oauth-provider 1.x, agents (Cloudflare Agents SDK), zod.
Dashboard Worker
dashboard/ holds a separate Worker, lastfm-mcp-stats, with its own wrangler.toml, tests and tsconfig.json. It's the private usage dashboard at stats.lastfm-mcp.com. The runbook for provisioning, deploying and rotating its token is in dashboard/README.md.
- It's deployed by hand with
npm run dashboard:deploy, never by CI, and has noworkers.devor preview URL. CI lints and tests it but doesn't deploy it. - Cloudflare Access sits in front of it, and the Worker verifies the Access JWT on every request too. An empty
ACCESS_AUDrefuses everything. - It reads production
OAUTH_KVonly through the KV REST API, with a read-only token (Account Analytics Read and Workers KV Storage Read), and never writes it. It writes only its ownDASH_KV, which holds no username, client URL or registered client name. Active users are counted fromtoken:key names, stored only as HMAC-SHA256 hashes of user IDs keyed with theACTIVE_USER_HMAC_KEYsecret, for 31 days. - It imports
labelForClientandCLIENT_LABELSfromsrc/analytics/clientLabel.ts, so the dashboard and theTOOL_EVENTSwriter label clients from the same fixed list.
OAuth Notes
getOAuthProvider(origin)builds one provider per request origin (custom domain, workers.dev, localhost) and is called with a per-request copy ofenv. The provider stores its helpers onenv.OAUTH_PROVIDERonly when unset, so a sharedenvwould serve the first origin's helpers to every later origin.src/auth/resource-indicator.tsrewrites exactlyresource=<origin>/mcpto the origin on/authorizeand/oauth/token. 1.x answers any other path withinvalid_target, which clients don't recover from. Upstream request: cloudflare/workers-oauth-provider#430.- Plain-http requests to non-loopback hosts get a 308 to https before they reach the provider, which throws on an http resource outside loopback.
/authorizeshows the consent page (src/auth/consent-page.ts) before redirecting to Last.fm.CONSENT_SECRETsigns the cookie that remembers an approval for a year; when it's missing or shorter than 32 characters, approvals aren't remembered and sign-in still works.- Errors on
/authorizerender on this origin and are never redirected to the client'sredirect_uri: registration is open, so redirecting would make the server an open redirector. - Two per-IP budgets, both failing open:
/mcpgets 60 requests a minute from a KV counter inMCP_RL(src/utils/rateLimit.ts), andPOST /oauth/registergets 5 a minute from theREGISTRATION_RATE_LIMITERRate Limiting binding (src/utils/registrationRateLimit.ts). The binding's limit and period live inwrangler.toml, once per environment. Its counts are approximate and per Cloudflare location, so it slows a flood without capping it (on staging it admitted 59 of 100 concurrent registrations from one IP); the[OAUTH] client registeredlog line is what makes abuse visible. - Grants expire 30 days after sign-in (the library's refresh-token default), so a
grant_not_foundorinvalid_grantafter about a month is expected.
Recommendations
get_music_recommendations runs inside one request policy (src/utils/lastfmRequestPolicy.ts): at most 40 Last.fm HTTP requests including retries, 4 in flight, one retry, and a hard 8-second deadline that also limits how long the call waits on cache reads and writes. The first persistent rate limit (HTTP 429 after its retry, or Last.fm error 29) stops queued and later requests; requests already in flight may finish. Other tools never run under a policy. The ranked candidate list is cached per user and genre for an hour under a v2: key and never includes exclude; a partial list is never cached. Design and rationale: the recommendations design.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

