在对MCP SDK的 GetPromptResult['messages'] 使用for...in进行遍历时,字符串类型上不存在属性 'content'
我在使用MCP(Model Context Protocol)TypeScript SDK(@modelcontextprotocol/sdk)并尝试遍历从 getPrompt() 返回的消息。当我把结果强制转换为 GetPromptResult["messages"] 并对其进行遍历时,TypeScript会报告 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;
}
}
如果把message.content放鼠标悬停上,它会显示
Property 'content' does not exist on type 'string'
我期望 message 的类型被标注为 { role: "user" | "assistant", content: { type: "text", text: string } | ... },因为这正是把鼠标悬停在 GetPromptResult["messages"] 上时所显示的。
TypeScript实际上推断 message 的类型为 string。
环境:
@modelcontextprotocol/sdkv1.29.0- TypeScript 6.0.2
- Node.js搭配
"module": "nodenext"
为什么 for...in 会把循环变量标记为 string,即使数组已显式强制转换?以及在保持对象类型的前提下,遍历 GetPromptResult["messages"] 的正确方法是什么?
解决方案
问题出在你代码片段的这一段:
for (const message in promptMessage as GetPromptResult["messages"]) {
const msg = message.content;
}
使用关键字 "in",实际上得到的是JSON键,而不是值。在你的代码中,你需要改成:
for (const message in promptMessage as GetPromptResult["messages"]) {
const msg = promptMessage[message].content;
}
但一个更简单的解决方案是把 "in" 换成 "of", 这样就能得到你想要的结果:
for (const message of promptMessage as GetPromptResult["messages"]) {
const msg = message.content;
}
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。