Skip to main content
Glama

read

Retrieve recent messages from the most recent OpenCode session on a specified instance. Use this to review conversation history without sending a new message.

Instructions

Read the last few messages from the most recent opencode session on an instance. Use this to see what has been happening without sending a new message.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
instanceYesInstance name (exact or fuzzy substring match)
message_limitNoMax number of messages to retrieve (default 10)

Implementation Reference

  • Registration of the 'read' tool with its name, description, and Zod schema for parameters (instance and message_limit). Registered via server.tool().
    server.tool(
      'read',
      'Read the last few messages from the most recent opencode session on an instance. Use this to see what has been happening without sending a new message.',
      {
        instance: z
          .string()
          .describe('Instance name (exact or fuzzy substring match)'),
        message_limit: z
          .number()
          .optional()
          .default(10)
          .describe(
            'Max number of messages to retrieve (default 10)',
          ),
      },
  • Handler function for the 'read' tool. Resolves the instance, finds the most recent session, fetches messages via GET /session/{id}/message?limit={limit}, formats them (role, time, text parts, tool parts), and returns the formatted text.
      async ({ instance: query, message_limit }) => {
        try {
          const { instance } = registry.resolveInstance(query)
          const baseUrl = instance.url
    
          // Find the most recently updated session
          const session = await findMostRecentSession(baseUrl)
          if (!session) {
            return {
              content: [
                {
                  type: 'text',
                  text: `No sessions found on ${instance.name}.`,
                },
              ],
            }
          }
    
          // Fetch recent messages
          const msgRes = await fetch(
            `${baseUrl}/session/${session.id}/message?limit=${message_limit}`,
          )
          if (!msgRes.ok) {
            return {
              content: [
                {
                  type: 'text',
                  text: `Failed to fetch messages from ${instance.name}.`,
                },
              ],
              isError: true,
            }
          }
    
          const messages = (await msgRes.json()) as Array<{
            info: {
              role: string
              time: { created: number }
            }
            parts: Array<{
              type: string
              text?: string
              tool?: string
              state?: { status: string }
            }>
          }>
    
          if (messages.length === 0) {
            return {
              content: [
                {
                  type: 'text',
                  text: `Session "${session.title ?? '(untitled)'}" on ${instance.name} has no messages.`,
                },
              ],
            }
          }
    
          // Check status
          const { busySessionId } = await getInstanceStatus(baseUrl)
          const status =
            busySessionId === session.id ? 'busy' : 'idle'
    
          const lines = [
            `**${instance.name}** — "${session.title ?? '(untitled)'}" (${status})`,
            '',
          ]
    
          for (const msg of messages) {
            const role =
              msg.info.role === 'user' ? 'User' : 'Assistant'
            const time = new Date(
              msg.info.time.created,
            ).toLocaleTimeString()
    
            const textParts = msg.parts
              .filter((p) => p.type === 'text' && p.text)
              .map((p) => p.text!)
              .join('\n')
    
            const toolParts = msg.parts
              .filter((p) => p.type === 'tool')
              .map(
                (p) =>
                  `  [tool: ${p.tool} → ${p.state?.status ?? '?'}]`,
              )
    
            lines.push(`**${role}** (${time}):`)
            if (textParts) lines.push(textParts)
            if (toolParts.length > 0) lines.push(toolParts.join('\n'))
            lines.push('')
          }
    
          return {
            content: [{ type: 'text', text: lines.join('\n') }],
          }
        } catch (err) {
          return {
            content: [
              { type: 'text', text: `Error: ${(err as Error).message}` },
            ],
            isError: true,
          }
        }
      },
    )
  • Zod schema defining inputs for the 'read' tool: 'instance' (required string) and 'message_limit' (optional number, default 10).
    {
      instance: z
        .string()
        .describe('Instance name (exact or fuzzy substring match)'),
      message_limit: z
        .number()
        .optional()
        .default(10)
        .describe(
          'Max number of messages to retrieve (default 10)',
        ),
    },
  • Helper function findMostRecentSession() used by the 'read' tool to locate the most recently updated session on an instance before fetching messages.
    async function findMostRecentSession(
      baseUrl: string,
    ): Promise<SessionInfo | undefined> {
      try {
        const res = await fetch(`${baseUrl}/session`)
        if (!res.ok) return undefined
        const sessions = (await res.json()) as SessionInfo[]
        if (sessions.length === 0) return undefined
        sessions.sort((a, b) => b.time.updated - a.time.updated)
        return sessions[0]
      } catch {
        return undefined
      }
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description must carry the full burden of behavioral disclosure. It only states the action and does not disclose traits such as idempotency, side effects, authentication requirements, rate limits, or error behaviors. This is a significant gap for a read operation.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is concise, consisting of two sentences: the first states the core function, and the second provides usage context. There is no redundant information.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a simple tool with two parameters and no output schema, the description covers the purpose and usage context adequately. However, it lacks details about edge cases (e.g., no session found, empty messages) and does not specify the format of the returned messages. Slightly incomplete but sufficient.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, with both parameters ('instance' and 'message_limit') described adequately in the schema. The tool description adds context about the 'most recent opencode session,' providing minor added value beyond the schema but not enough to substantially raise the score.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool reads 'the last few messages from the most recent opencode session on an instance,' specifying the action (read), resource (messages), and scope. This verb+resource structure effectively distinguishes it from sibling tools 'instances' and 'send'.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides a clear use case ('to see what has been happening without sending a new message') but does not explicitly state when not to use this tool or compare it to alternatives. It implies reading versus sending but lacks explicit exclusion criteria.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/klutometis/opencode-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server