agentleFS
rianvdmrianvdm/lastfm-mcp/CLAUDE.md

lastfm-mcp

CLAUDE.md49 starsChanged 10 months agoMITView on GitHub

Cloudflare Worker implementing a Model Context Protocol (MCP) server that connects AI assistants to Last.fm listening data. Runs on workerd with KV-backed persistence for sessions, caching, rate limits, and logs. Test runner: vitest 4 with @cloudflare/vitest-pool-workers ≥0.15 (runs in workerd/miniflare). Requires Node 22 (see .nvmrc); the config uses the cloudflareTest() plugin shape, not the removed defineWorkersConfig. Every file (source and test) must have exactly two // ABOUTME: comment lines at the top. Line 1 describes WHAT the file is. Line…

The file

We split this CLAUDE.md into the rules it gives an agent

6 rules. About 0 are common, 2 are distinctive, and 4 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈2

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 4

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

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

    line 22
  2. Very specific:

    Use import type for type-only imports

    line 71
  3. Distinctive:

    No file extensions on relative imports (Wrangler bundles them)

    line 72
  4. Distinctive:

    No path aliases — all relative paths

    line 74
  5. Very specific:

    Always use error instanceof Error ?

    line 107
  6. Very specific:

    Test stubs for ajv in test/stubs/ (workerd can't run ajv CJS modules)

    line 133

≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.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
CLAUDE.md

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code 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 KV-backed persistence for sessions, caching, rate limits, and logs.

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
npm run deploy:prod      # Deploy to production
npm run lint             # ESLint (src/**/*.ts)
npm run format           # Prettier --write
npm run format:check     # Prettier --check (CI)
npm run cf-typegen       # Regenerate Worker type bindings (run after changing wrangler.toml; produces worker-configuration.d.ts — generated, do not edit by hand)

Running Tests

Test runner: vitest 4 with @cloudflare/vitest-pool-workers ≥0.15 (runs in workerd/miniflare). Requires Node 22 (see .nvmrc); the config uses the cloudflareTest() plugin shape, not the removed defineWorkersConfig.

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.

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

Four 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'
  • Test stubs for ajv in test/stubs/ (workerd can't run ajv CJS modules)

Architecture Overview

src/
  index-oauth.ts        # Sole Worker entry point (OAuth 2.1 + session hybrid auth)
  marketing-page.ts     # Landing page HTML (served at /)
  auth/                 # JWT, Last.fm auth flow, OAuth 2.1 handler
  clients/              # Last.fm API client + caching decorator
  mcp/                  # MCP SDK server, tools (public + authenticated), prompts, resources
  types/                # Shared types: Env, MCP protocol, Last.fm catalogs
  utils/                # Cache, rate limiting, retry, logging, security, mood mapping

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.

Key dependencies: @modelcontextprotocol/sdk, @cloudflare/workers-oauth-provider, agents (Cloudflare Agents SDK), zod.

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.