agentleFS
rianvdmrianvdm/lastfm-mcp/AGENTS.md

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.

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
  1. Distinctive:

    After it merges, tag that merge commit and create the GitHub release.

    line 34
  2. Very specific:

    Test runner: vitest 4 with @cloudflare/vitest-pool-workers 0.22 (runs in workerd/miniflare).

    line 40
  3. Very specific:

    Use import type for type-only imports

    line 102
  4. Distinctive:

    No file extensions on relative imports (Wrangler bundles them)

    line 103
  5. Distinctive:

    No path aliases — all relative paths

    line 105
  6. Very specific:

    Always use error instanceof Error ?

    line 138

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
AGENTS.md

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 does

Deploys 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:

  1. In one PR, bump version in package.json, package-lock.json and server.json, and SERVER_VERSION in src/mcp/protocol.ts. server_info, the server card and /health report SERVER_VERSION; test/server-json.test.ts fails if server.json drifts from it. In the same PR, update LATEST_RELEASE in src/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) and LANDING_PAGE_UPDATED; test/pages/landing.test.ts fails if its version drifts from SERVER_VERSION.
  2. After it merges, tag that merge commit and create the GitHub release.
  3. 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, then mcp-publisher publish. The key proves control of the domain through the apex v=MCPv1 TXT record; it's kept outside the repo. A published version can't be changed, so a listing-only fix publishes a prerelease such as 2.8.0-1.
  4. 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 hood sections. 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.yml posts 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 each
npm 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 directory

Code 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.html and the src/pages/share/*.html sources put both lines in one HTML comment right after <!doctype html>.
  • src/pages/llms.md has 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

  1. External/third-party packages first
  2. Blank line
  3. 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 type for 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 from agents/mcp/server
  • No path aliases — all relative paths

Naming Conventions

ThingConventionExample
Files (source)camelCase or kebab-casecachedLastfm.ts, oauth-handler.ts
Files (test)Match source + .test.tsretry.test.ts, index-oauth.test.ts
Directorieslowercaseauth/, mcp/, utils/
FunctionscamelCasecreateMcpServer, fetchWithRetry
ClassesPascalCaseLastfmClient, SmartCache
Interfaces/TypesPascalCase, no prefixEnv, SessionPayload (not IEnv)
EnumsPascalCase + PascalCase membersErrorCode.ParseError
ConstantsUPPER_SNAKE_CASESERVER_VERSION, PROTOCOL_VERSION
VariablescamelCasesessionId, 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., LastfmTrack in src/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:

  1. HTTP handlers — try/catch, log with console.error, return Response with status code
  2. MCP tools — try/catch, return toolError('tool_name', error) from src/mcp/tools/error-handler.ts
  3. 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 in test/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, breadcrumbs

Single 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 no workers.dev or 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_AUD refuses everything.
  • It reads production OAUTH_KV only 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 own DASH_KV, which holds no username, client URL or registered client name. Active users are counted from token: key names, stored only as HMAC-SHA256 hashes of user IDs keyed with the ACTIVE_USER_HMAC_KEY secret, for 31 days.
  • It imports labelForClient and CLIENT_LABELS from src/analytics/clientLabel.ts, so the dashboard and the TOOL_EVENTS writer 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 of env. The provider stores its helpers on env.OAUTH_PROVIDER only when unset, so a shared env would serve the first origin's helpers to every later origin.
  • src/auth/resource-indicator.ts rewrites exactly resource=<origin>/mcp to the origin on /authorize and /oauth/token. 1.x answers any other path with invalid_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.
  • /authorize shows the consent page (src/auth/consent-page.ts) before redirecting to Last.fm. CONSENT_SECRET signs 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 /authorize render on this origin and are never redirected to the client's redirect_uri: registration is open, so redirecting would make the server an open redirector.
  • Two per-IP budgets, both failing open: /mcp gets 60 requests a minute from a KV counter in MCP_RL (src/utils/rateLimit.ts), and POST /oauth/register gets 5 a minute from the REGISTRATION_RATE_LIMITER Rate Limiting binding (src/utils/registrationRateLimit.ts). The binding's limit and period live in wrangler.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 registered log line is what makes abuse visible.
  • Grants expire 30 days after sign-in (the library's refresh-token default), so a grant_not_found or invalid_grant after 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.

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.