AINextJSSanity2 MIN READ
15.03.2026
.md

Serving Your Blog as Markdown So AI Agents Can Actually Read It

Last updated: 31.05.2026

🎧

Serving Your Blog as Markdown So AI Agents Can Actually Read It

Audio Narration

ai agent

Why AI Agents Struggle with HTML

HTML is for browsers. When an AI agent fetches a blog post it gets navigation bars, scripts, cookie banners, and footer links tangled around the actual content. Markdown gives agents clean, structured text they can parse and reason over without stripping noise. Two patterns make this work: append .md to any post URL, or send an Accept: text/markdown header on a normal request.

Wiring It Up in next.config.ts

Next.js rewrites handle both patterns in beforeFiles. The first rule maps the .md URL suffix to the internal route. The second matches the same destination when the Accept header contains text/markdown:

1rewrites: async () => ({
2  beforeFiles: [
3    // Explicit .md URL
4    { source: '/posts/:slug', destination: '/md/posts/:slug' },
5    // Content negotiation via Accept header
6    {
7      source: '/posts/:slug',
8      destination: '/md/posts/:slug',
9      has: [{ type: 'header', key: 'accept', value: '(.*)text/markdown(.*)' }],
10    },
11  ],
12})

The Route Handler

The internal /md/posts/[slug] route fetches the post from Sanity via sanityFetch, converts it to Markdown, and returns it with the correct Content-Type and a 60-second cache:

1export async function GET(request, { params }) {
2  const data = await sanityFetch({ query: postQuery, params: await params })
3  if (!data) return new Response('Not found', { status: 404 })
4
5  const markdown = buildPostMarkdown(
6    data,
7    process.env.NEXT_PUBLIC_SITE_URL
8  )
9  return new Response(markdown, {
10    headers: {
11      'Content-Type': 'text/markdown; charset=utf-8',
12      'Cache-Control': 'public, max-age=60, stale-while-revalidate=300',
13    },
14  })
15}

Building the Markdown Output

buildPostMarkdown assembles the full document: title as H1, canonical URL, hero image if present, auto-generated summary, body converted from Portable Text via @portabletext/markdown, and an optional image gallery.

1export function buildPostMarkdown(post, baseUrl) {
2  const parts = []
3  parts.push(`# ${post.title}`)
4  parts.push(`**URL:** ${baseUrl}/${post.path}`)
5  if (post.mainImage) {
6    parts.push(`![${post.mainImage.alt}](${post.mainImage.asset?.url})`)
7  }
8  if (post.autoSummary) parts.push(`**Summary:** ${post.autoSummary}`)
9  if (post.body) parts.push(convertToMarkdown(post.body, baseUrl))
10  return parts.join('\n')
11}

Code Blocks in Portable Text

Sanity stores code snippets as custom blocks with _type: "code". Here is a real example from the TypeScript Pro Essentials post on this blog, as it lives in Portable Text:

1{
2  "_type": "code",
3  "language": "ts",
4  "code": "type StrictOmit<T, K extends keyof T> = Omit<T, K>;"
5}

@portabletext/markdown handles this block type and renders it as a fenced code block with the language tag preserved — exactly what an AI agent or syntax highlighter expects:

1```ts
2type StrictOmit<T, K extends keyof T> = Omit<T, K>;
3```

The Posts Index

/posts.md lists all published posts with titles, dates, authors, summaries, and links. It works as a machine-readable sitemap — an agent can fetch it first to discover what is available, then follow links to individual posts as Markdown.

Practical Usage

1# .md URL suffix
2curl https://andreskristensen.blog/posts/reading-time-sanity-blog.md
3
4# Accept header (content negotiation)
5curl -H 'Accept: text/markdown' https://andreskristensen.blog/posts/reading-time-sanity-blog
6
7# Posts index — discover all posts
8curl https://andreskristensen.blog/posts.md

The .md URL approach is simpler for linking and sharing. The Accept header approach works with tools that fetch standard URLs but can override headers — useful for MCP servers and AI clients.

Inspired by Sanity's field guide on serving content to agents.

Continue Reading
A closed notebook with a wrench, a magnifying glass and a ruler tucked under its elastic band.
AI3 MIN

My blog has tools now: WebMCP for browser agents

The blog builds on its Markdown-first approach by adding WebMCP, a draft W3C technology that lets web pages expose structured tools to browser-based agents. Rather than forcing an agent to inspect pages, infer URLs, and construct requests, WebMCP provides a concise list of callable tools registered through `document.modelContext.registerTool()`. Chrome supports it experimentally through an origin trial beginning with version 149. Every page on the blog offers three read-only tools: `list_posts`, which returns recent posts with optional category and limit filters; `get_post`, which retrieves a post’s full Markdown by slug; and `list_categories`, which lists categories and post counts. These tools simply fetch existing public Markdown endpoints, so the same information remains accessible without WebMCP. Users can inspect and invoke the tools in Chrome DevTools under Application > WebMCP or query them from the console. Agents can also access them through Chrome DevTools MCP, while an inspector extension supports prompting with Gemini. However, current access depends on flags, experimental options, or an origin trial, and tools are visible only while a page is open. Keeping them as thin wrappers ensures the blog remains functional if WebMCP changes or disappears.

Read post
A school report card with a pie chart, 68 shaded in teal and the rest filled in with red pen to make 100.
AISEOClaude4 MIN

From 68 to 100: making my blog readable for AI agents

Is Agentic is a free tool that evaluates how accessible a website is to AI agents. It scans a URL, assigns a score out of 100, provides supporting evidence, and recommends fixes across essential, recommended, and bonus checks. The author’s blog initially scored 68. Using the report and Claude Code, the author added Markdown versions of posts, listings, the homepage, and error pages so agents could access content and recover from broken links more easily. Other improvements included structured data identifying the site and author, a clearer title, properly ordered headings, and an updated llms.txt file explaining when the personal blog is an appropriate source. Reviewing the site from an agent’s perspective also revealed a hidden linking bug: Markdown posts pointed to nonexistent /post/ URLs instead of /posts/. After fixes, the site scored 100, although that total included bonus points and concealed two recommended-check gaps. Contact and Privacy pages were added, while one search-ranking check remains unresolved because its results differ from Google’s. Website owners can test their own sites at is-agentic.com, prioritize failed essential checks, implement fixes, and rescan. Reports retain the same shareable URL while displaying the latest results.

Read post