Vibe coding with Claude Code course ยท Module 12: Medium clone

The Lookout on the Mast: Production Errors, Sentry and MCP

12 min read
In this lesson11

After lesson 11_3 you asked Claude for excerpts, the first lines of text under each title on the publication page: "Under the titles show the first paragraph, at most 160 characters, an excerpt function in lib/excerpt.ts". If you have not shipped it yet, do it now. Lint and build passed, the commit went out. A week later Mary Read changed the only paragraph of her text in the Galley into a quote. From that moment the page /publications/galley answers every reader with a 500 error, and you know nothing about it, because everything works for you. A reader does not file a report, they sail away. You need a lookout on the mast: a service that sees every error in production and raises the alarm at once.

What you will learn

  • connect Sentry with the wizard and read in Cursor every file it added;
  • keep the Sentry token out of the conversation with Claude and out of the repository;
  • debug a production error with Claude Code: the cause, a test that reproduces it, and only then the fix;
  • tell error.tsx, global-error.tsx and your own ErrorBoundary apart;
  • connect the Sentry MCP server and know when a plain CLI is enough.

You run the Sentry wizard yourself

Sentry collects errors from the app together with a stack trace, that is a list of functions, files and lines the program went through before it fell. You need your own account and project in Sentry. The official guide for Next.js recommends the wizard (as of November 2026):

npx @sentry/wizard@latest -i nextjs

You type this command yourself, in a separate terminal tab in Cursor. The wizard logs you in through the browser, asks about performance tracking, session replays and an example page, and at the end saves a token. From lesson 8_5 you know that the output of a command run with ! lands in the conversation with Claude, and here is nothing Claude needs to see.

According to the Sentry docs the wizard saves the token in the file .env.sentry-build-plugin and adds that file to .gitignore. With this token the build uploads source maps to Sentry, that is files that translate compiled code back into your files and lines. The token is a secret. The DSN is different: it is the address the SDK sends errors to, and it goes to the browser of every reader, so it is no secret. The rule Read(./.env.*) from lesson 8_4 covers the token file too, because the star matches every name after .env.. If this project does not have it yet, copy the rules into .claude/settings.json before you run the wizard.

What the wizard added

Open the Source Control panel in Cursor and read the diff file by file before you commit. The wizard creates three starter files, because Next.js runs code in three environments: instrumentation-client.ts for the browser, sentry.server.config.ts for Node.js and sentry.edge.config.ts for the Edge environment. The browser file looks like this:

// instrumentation-client.ts
import * as Sentry from "@sentry/nextjs";

Sentry.init({
  dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
  tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
});

export const onRouterTransitionStart = Sentry.captureRouterTransitionStart;

The wizard writes the DSN directly, and the docs also allow a public variable NEXT_PUBLIC_SENTRY_DSN. tracesSampleRate says what share of requests Sentry records as performance traces. The wizard writes 1, that is all of them, and the docs recommend lowering the value in production and show 0.1. It does not apply to errors: for them a separate option sampleRate sends every one by default. The most important file is instrumentation.ts:

// instrumentation.ts
import * as Sentry from "@sentry/nextjs";

export async function register() {
  if (process.env.NEXT_RUNTIME === "nodejs") {
    await import("./sentry.server.config");
  }
  if (process.env.NEXT_RUNTIME === "edge") {
    await import("./sentry.edge.config");
  }
}

export const onRequestError = Sentry.captureRequestError;

register loads the configuration that fits the environment. onRequestError is a Next.js hook that, according to the Sentry docs, catches errors from Server Components, API routes and middleware, exactly the kind of error Mary's change caused. Further in the diff: app/global-error.tsx with Sentry.captureException in useEffect and next.config.ts wrapped in withSentryConfig from @sentry/nextjs/config, which uploads the maps during the build.

The first alarm

The docs tell you to check the installation on the wizard's /sentry-example-page: the button "Throw Sample Error" throws an error in the browser and on the server. Then reproduce the real case: in lib/articles.ts change the type of the only text block a3 from "paragraph" to "quote", run npm run build && npm start and open /publications/galley.

We had no Sentry account, so the DSN pointed at a local receiver that pretended to be Sentry. It received a report: TypeError: Cannot read properties of undefined (reading 'text'), mechanism auto.function.nextjs.on_request_error, route /publications/[slug]. The frames of the trace pointed at the file _next/server/chunks/ssr/...js, line 2: that is what a trace without source maps looks like. In npm run dev the same error in the terminal pointed at your code:

โจฏ TypeError: Cannot read properties of undefined (reading 'text')
    at excerpt (lib/excerpt.ts:5:54)
    at <unknown> (app/publications/[slug]/page.tsx:20:18)

With source maps Sentry shows your files and lines in the trace, which is why the token from the wizard is worth the trouble.

Request for Claude Code: the cause first

You know the order from lessons 2_8 and 4_1: the cause, a test that fails, and only then the fix.

Request for Claude Code:

Sentry: /publications/galley returns 500 since the only paragraph
of text a3 became a quote. Trace:
TypeError: Cannot read properties of undefined (reading 'text')
    at excerpt (lib/excerpt.ts:5:54)
    at <unknown> (app/publications/[slug]/page.tsx:20:18)
First describe the cause, do not change the code. Then add to
lib/excerpt.test.ts a test that reproduces the bug, run it and show
that it fails. Write the fix only after my "ok": a text without a
paragraph gets an excerpt from its first block, a text without
blocks gets an empty one.

What Claude wrote: the test and the fix

The cause fits in one sentence: excerpt assumes that every text has a paragraph, and the ! sign after find(...) promises TypeScript that something will be found. That promise passed npm run lint and npx tsc --noEmit for us. Open lib/excerpt.test.ts in Cursor:

// lib/excerpt.test.ts
test("a poem made only of quotes: the excerpt comes from the first quote", () => {
  const poem = article([{ id: "q1", type: "quote", text: "The stars are a clock." }]);
  expect(excerpt(poem)).toBe("The stars are a clock.");
});

article is a helper of the test that takes a sample article and swaps its blocks. Before the fix the test failed with the same TypeError as production, so it really reproduces the bug. After your "ok" Claude changed the function:

// lib/excerpt.ts
export function excerpt(article: Article, max = 160): string {
  const block = article.blocks.find((b) => b.type === "paragraph") ?? article.blocks[0];
  if (!block) return "";
  const text = block.text.trim();
  return text.length > max ? text.slice(0, max - 1).trimEnd() + "โ€ฆ" : text;
}

?? takes the first block of any type when there is no paragraph, and an empty article gets an empty excerpt. Both cases are decisions you made yourself in the request, and both have a test. For us all tests passed after the fix.

A typical agent mistake: a try/catch that silences the alarm

Instead of the cause an agent may silence the symptom:

// lib/excerpt.ts (the agent's version)
try {
  const text = article.blocks.find((b) => b.type === "paragraph")!.text;
  return text.length > max ? text.slice(0, max - 1).trimEnd() + "โ€ฆ" : text;
} catch {
  return "";
}

For us this version passed lint and tsc, and the Galley page answered 200 with an empty excerpt. Nothing would reach Sentry, because according to its docs an error that is caught and not thrown further never gets there. Only the test told the truth: expected '' to be 'The stars are a clock.'. An empty catch is a lookout who fell asleep on the mast.

Three guards: error.tsx, global-error.tsx and ErrorBoundary

An error during page rendering is caught by an error boundary: a component that shows fallback text in place of the broken part. Next.js gives you two ready ones. error.tsx in a route folder covers its page and nested layouts. global-error.tsx is the last line of defence when the root layout breaks, which is why it has its own <html> and <body>. The Sentry docs warn: an error caught by error.tsx does not reach Sentry by itself, so every such boundary calls Sentry.captureException.

You place your own boundary around one part of the page, so that its failure does not take the rest down. The React docs say that a boundary is written as a class with two methods: static getDerivedStateFromError changes the state to show the fallback text, and componentDidCatch is for sending a report:

// components/ErrorBoundary.tsx
export default class ErrorBoundary extends Component<Props, { hasError: boolean }> {
  state = { hasError: false };

  static getDerivedStateFromError() {
    return { hasError: true };
  }

  componentDidCatch(error: Error, info: ErrorInfo) {
    Sentry.captureException(error, { contexts: { react: { componentStack: info.componentStack } } });
  }

  render() {
    if (this.state.hasError) return this.props.fallback;
    return this.props.children;
  }
}

The file starts with "use client", and Props is fallback and children. A test with a component that throws an error showed us the order: getDerivedStateFromError sets hasError, render draws the fallback text, and only then React calls componentDidCatch. On the article page the boundary wraps the claps, so their failure does not take the text away:

// app/articles/[id]/page.tsx
<ErrorBoundary fallback={<p className="text-sm text-gray-500">Claps are temporarily down.</p>}>
  <ClapButton articleId={article.id} initial={claps} />
</ErrorBoundary>

Two limits of this boundary, also from the React docs: it does not catch errors in event handlers (for example in onClick) or in asynchronous code, and in the production build an error caught in componentDidCatch does not go any higher. Without captureException Sentry would not see it. Since version 16.3 Next.js also has catchError from next/error, which adds retry and lets notFound() through, but the class from React is the foundation you practise in the task.

The lookout in the conversation: the Sentry MCP server

Until now you copied the trace from Sentry into the request. MCP (Model Context Protocol) is an open standard through which Claude Code connects to other tools: an MCP server gives Claude tools for reading and acting in another system. The Claude Code docs advise connecting a server exactly when you catch yourself pasting data from another tool, for example from a monitoring panel. The page of the Sentry server (mcp.sentry.dev) lists searching errors, performance analysis, issue triage, reading docs and managing projects. You type the command in the terminal, in the project folder:

claude mcp add --transport http --scope project sentry https://mcp.sentry.dev/mcp/your-organization/captains-chronicle

--transport http is, according to the docs, the recommended way to connect to a remote server. The last two parts of the address narrow the server to one organization and one project, which the Sentry page recommends. The scope decides where the configuration goes: local (the default) only for you and this project in ~/.claude.json, user for all your projects in the same file, project to the .mcp.json file in the repository, for the whole crew. You choose project, because the file holds only the address, with no token. For us it created this .mcp.json:

{
  "mcpServers": {
    "sentry": {
      "type": "http",
      "url": "https://mcp.sentry.dev/mcp/your-organization/captains-chronicle"
    }
  }
}

claude mcp list showed โธ Pending approval next to the server, asking us to run claude: a server from .mcp.json waits until you approve it in a session, because a cloned repository cannot switch on servers by itself. In a session /mcp shows the status of servers, guides you through the OAuth login in the browser, lets you disable a server and clear the login. Every crew member logs in with their own account, so Claude sees in Sentry only what your account can access. Now you ask:

Fetch from Sentry the unresolved errors from the last 24 hours. For
each one give the title, the number of occurrences and the files of
our repository that the trace points at. Change nothing.

You open every file it points at in Cursor and compare it with the report. Error messages can contain text typed by strangers, and the Claude Code docs warn against prompt injection through servers that read outside content. It is data to read, not orders.

First, though, ask whether you need MCP at all. The Claude Code best practices say: if a system has a CLI, it is usually the simplest way, and MCP is for systems without one. For GitHub gh is enough, and Claude runs it like any command. Sentry also has its own CLI (sentry, described at cli.sentry.dev), so here you have a choice too. A remote MCP server does not require installing anything on your computer.

Captain's review

  1. A secret outside the repository. git status does not show .env.sentry-build-plugin, and the diff holds no token.
  2. Sampling. tracesSampleRate in production did not stay at 1.
  3. A test before the fix. The excerpt test failed before the change and passes after it. A test that passes at once proves nothing.
  4. Nothing silenced. Search the project (Cmd+Shift+F) for catch: every new catch either throws the error further or calls Sentry.captureException.
  5. Boundaries report. Every error.tsx and every ErrorBoundary contains captureException.

Next step

Ask for a commit "Sentry, an excerpt without a paragraph and an ErrorBoundary around claps". Then: "Add @app/articles/[id]/error.tsx with a Try again button through retry and with Sentry.captureException in useEffect", as in lesson 3_4. In the editor below waits a publication page with a fake Sentry: trigger the excerpt error, switch on the agent's bug "hide the error in try/catch" and compare what the reader sees with what the lookout sees.

Remember: a lookout does not repair the ship, but without him nobody knows that water is already pouring into the hold.

Code for this lesson: App.jsx
// A publication page with a fake Sentry: excerpts, an error boundary and the agent's try/catch mistake
import { Component, useState } from 'react';

const ARTICLES = [
  { id: 'a1', title: 'How to Survive a Storm on the Atlantic', text: 'The storm came at night while the crew slept after a long watch.' },
  { id: 'a2', title: 'The Treasure Map That Never Was', text: 'The map had three crosses and no treasure.' },
  { id: 'a3', title: "The Ship's Cook Advises: Hardtack for Six Weeks", text: 'Hardtack must be hard as the deck, or it will not survive the voyage.' },
];

const VERSIONS = [
  { key: 'agent', label: 'Version with ! (a paragraph is always there)' },
  { key: 'trycatch', label: 'Agent mistake: hide the error in try/catch' },
  { key: 'fixed', label: 'Fix: the first block when there is no paragraph' },
];

function excerpt(article, version) {
  if (version === 'trycatch') {
    try {
      return article.blocks.find((b) => b.type === 'paragraph').text;
    } catch {
      return '';
    }
  }
  if (version === 'agent') {
    return article.blocks.find((b) => b.type === 'paragraph').text;
  }
  const block = article.blocks.find((b) => b.type === 'paragraph') ?? article.blocks[0];
  return block ? block.text : '';
}

// An error boundary as in the lesson. It calls onReport instead of Sentry.captureException.
class ErrorBoundary extends Component {
  state = { hasError: false };

  static getDerivedStateFromError() {
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    this.props.onReport(error, info.componentStack);
  }

  render() {
    if (this.state.hasError) return this.props.fallback;
    return this.props.children;
  }
}

function ArticleList({ articles, version }) {
  return (
    <ul className="space-y-3">
      {articles.map((article) => {
        const lead = excerpt(article, version);
        return (
          <li key={article.id}>
            <p className="font-semibold">{article.title}</p>
            {lead ? (
              <p className="text-gray-700">{lead}</p>
            ) : (
              <p className="italic text-amber-700">(empty excerpt)</p>
            )}
          </li>
        );
      })}
    </ul>
  );
}

export default function App() {
  const [maryQuote, setMaryQuote] = useState(false);
  const [version, setVersion] = useState('agent');
  const [reports, setReports] = useState([]);
  const [attempt, setAttempt] = useState(0);

  const articles = ARTICLES.map((a) => ({
    id: a.id,
    title: a.title,
    blocks: [{ type: a.id === 'a3' && maryQuote ? 'quote' : 'paragraph', text: a.text }],
  }));

  function report(error, componentStack) {
    const match = /at (\w+)/.exec(componentStack || '');
    setReports((list) =>
      [{ n: list.length ? list[0].n + 1 : 1, name: error.name, message: error.message, component: match ? match[1] : '?' }, ...list].slice(0, 3),
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 p-4 text-gray-900">
      <div className="mx-auto max-w-xl space-y-4 rounded-xl bg-white p-4 shadow-sm">
        <header>
          <h1 className="text-2xl font-bold">Cape Chronicles and the Galley</h1>
          <p className="text-sm text-gray-500">Publication page: titles with excerpts</p>
        </header>
        <ErrorBoundary
          key={attempt + '-' + version + '-' + maryQuote}
          onReport={report}
          fallback={
            <div role="alert" className="rounded bg-red-50 p-3 text-red-800">
              This page lost its course. The reader sees this message instead of the list.
            </div>
          }
        >
          <ArticleList articles={articles} version={version} />
        </ErrorBoundary>
      </div>

      <div className="mx-auto mt-3 max-w-xl space-y-2 rounded-xl bg-gray-900 p-4 text-sm text-white">
        <label className="flex items-center gap-2">
          <input type="checkbox" checked={maryQuote} onChange={(e) => {
            setMaryQuote(e.target.checked);
            setReports([]);
          }} />
          Mary changes the only paragraph of text a3 into a quote
        </label>
        <fieldset className="space-y-1">
          <legend className="font-semibold">The excerpt function</legend>
          {VERSIONS.map((v) => (
            <label key={v.key} className="flex items-center gap-2">
              <input type="radio" name="version" checked={version === v.key} onChange={() => {
                  setVersion(v.key);
                  setReports([]);
                }} />
              {v.label}
            </label>
          ))}
        </fieldset>
        <button type="button" onClick={() => setAttempt((n) => n + 1)} className="rounded bg-gray-700 px-3 py-1">
          Refresh the page
        </button>
      </div>

      <div className="mx-auto mt-3 max-w-xl space-y-2 rounded-xl bg-white p-4 text-sm shadow-sm">
        <p className="font-semibold">Fake Sentry: {reports.length ? 'alarm!' : 'silence'}</p>
        {reports.length === 0 && (
          <p className="text-gray-500">No reports. Silence does not mean everything works: check the excerpts above.</p>
        )}
        <ul className="space-y-1">
          {reports.map((r) => (
            <li key={r.n} className="rounded bg-red-50 p-2 text-red-900">
              #{r.n} {r.name}: {r.message} (component: {r.component})
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
}

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. The Sentry wizard logs you in through the browser, asks questions and saves a token for uploading source maps. How do you run it?

  2. 2. In which method of a class ErrorBoundary do you send the report to Sentry?

Hands-on tasks in the game

  • Code editor

    Error Boundary with Sentry reporting

  • Vertical ordering

    Arrange what happens in a class ErrorBoundary when a component inside it throws an error during rendering:

  1. QuestionWho runs the Sentry wizard
  2. Coding taskPractice: Error Boundary with Sentry
  3. Put in orderThe order inside an error boundary
  4. QuestionWhere the boundary sends its report

Useful articles