ARTICLE AD BOX
I am using the MCP (Model Context Protocol) TypeScript SDK (@modelcontextprotocol/sdk) and trying to iterate over the messages returned from getPrompt(). When I cast the result to GetPromptResult["messages"] and loop over it, TypeScript reports Property 'content' does not exist on type 'string'.
/** * Checks if the user prompt is a slash command (e.g. "/format deposition.md"), fetches the corresponding MCP prompt, and returns the server-built messages. * Returns null if the query is not a slash command. * @param query User prompt (may start with a "/" command) * @param mcpClient Connected MCP Client instance * @returns Array of PromptMessages from the server, or null if not a command */ export const extractPromptCommand = async (query: string, mcpClient: Client) => { if(!query.startsWith("/")) return null; const [rawCommand, ...argParts] = query.slice(1).split(" "); const command = rawCommand?.trim(); const argument = argParts.join(" ").trim(); if(!command) return null; try { const { messages } = await mcpClient.getPrompt({ name: command, ...(argument && { arguments: { doc_id: argument } }) }) return messages; } catch(error: any) { throw new Error(`Prompt command "/${command}" failed: ${error.message}`); } } // Handling the "/" commands const promptMessage = await extractPromptCommand(prompt, mcpClient); if(promptMessage) { for (const message in promptMessage as GetPromptResult["messages"]) { const msg = message.content; } }If you hover the message.content it shows the
Property 'content' does not exist on type 'string'
I expected message to be typed as { role: "user" | "assistant", content: { type: "text", text: string } | ... } since that is exactly what hovering over GetPromptResult["messages"] shows.
TypeScript actually infers message is typed as string.
Environment:
@modelcontextprotocol/sdk v1.29.0
TypeScript 6.0.2
Node.js with "module": "nodenext"
Why does for...in type the loop variable as string even when the array is explicitly cast? And what is the correct way to iterate over GetPromptResult["messages"] while preserving the object type?
