Examples

File Operations

Simple example of file operations with MCP resources.

Overview

This page demonstrates a simple file operation pattern using MCP resources.

Read File Resource

Simple file reading resource:

server/mcp/resources/readme.ts
import { readFile } from 'node:fs/promises'
import { fileURLToPath } from 'node:url'

export default defineMcpResource({
  name: 'readme',
  title: 'README',
  uri: 'file:///README.md',
  metadata: {
    description: 'Project README file',
    mimeType: 'text/markdown',
  },
  handler: async (uri: URL) => {
    try {
      const filePath = fileURLToPath(uri)
      const content = await readFile(filePath, 'utf-8')

      return {
        contents: [{
          uri: uri.toString(),
          mimeType: 'text/markdown',
          text: content,
        }],
      }
    }
    catch (error) {
      return {
        contents: [{
          uri: uri.toString(),
          mimeType: 'text/plain',
          text: `Error reading file: ${error instanceof Error ? error.message : String(error)}`,
        }],
        isError: true,
      }
    }
  },
})

Next Steps