McpContentBlock class
MCP 工具回應內容區塊的抽象基底類別。
Azure Functions 函式庫會使用 instanceof McpContentBlock,將內容區塊與純使用者值區分開來,因此只有內建子類別(McpTextContent、McpResourceLinkContentMcpImageContentMcpAudioContentMcpResourceContent)的實例——或是延伸此類別的自訂子類別——才會被視為內容區塊。
像 { type: 'text', text: '...' } 是純物件的字面值 不會 被視為內容區塊,而是會被序列化成 JSON 文字。
以自訂內容區塊類型進行擴充
如果 MCP 規範新增了新的區塊類型——或你的情境需要自訂的——你可以在不更改任何函式庫的情況下推出自己的子類別。 轉換器只會檢查 instanceof McpContentBlock 並呼叫 JSON.stringify(block),這會促使你 toJSON() 產生線材有效載荷。
範例:新增一個假設性情形 VideoContent
import { McpContentBlock } from '@azure/functions';
export interface VideoContentInit {
data: string | Buffer | ArrayBuffer;
mimeType: string; // e.g. 'video/mp4'
durationMs?: number; // optional field from a hypothetical spec
}
export class VideoContent extends McpContentBlock {
readonly type = 'video' as const;
readonly data: string | Buffer | ArrayBuffer;
readonly mimeType: string;
readonly durationMs?: number;
constructor(init: VideoContentInit) {
super();
this.data = init.data;
this.mimeType = init.mimeType;
this.durationMs = init.durationMs;
}
toJSON(): Record<string, unknown> {
const out: Record<string, unknown> = {
type: this.type,
data: toBase64(this.data),
mimeType: this.mimeType,
};
if (this.durationMs !== undefined) out.durationMs = this.durationMs;
return out;
}
}
function toBase64(data: string | Buffer | ArrayBuffer): string {
if (typeof data === 'string') return data;
if (Buffer.isBuffer(data)) return data.toString('base64');
return Buffer.from(new Uint8Array(data)).toString('base64');
}
使用工具處理程式中的自訂區塊
// Single block
handler: async () => new VideoContent({ data: buf, mimeType: 'video/mp4' })
// Mixed with built-ins + structured content
handler: async () => new McpToolResponse({
content: [
new McpTextContent('Detected 3 scenes'),
new VideoContent({ data: buf, mimeType: 'video/mp4' }),
],
structuredContent: { scenes: 3, confidence: 0.92 },
})
圖書館為你做的事
-
instanceof McpContentBlock把你的子職業當成內建方塊一樣對待。 - 單區塊回傳會將您的字串傳播
type到外部結果;陣列則以 包裹為multi_content_result。 -
structuredContent處理、備援文字合成及 nullish 直通皆未變更。
你在子職業中必須掌握的重點
-
toJSON()必須回傳規格中對您的type. - 二進位有效載荷應該以 base64 編碼(
toJSON()見上方輔助工具)。toBase64 - 純物件字面值 無法 被識別——您必須建構一個實例。
屬性
| type |
方法
| toJSON() |
屬性詳細資料
type
type: string
屬性值
string
方法詳細資料
toJSON()
function toJSON(): Record<string, unknown>
傳回
Record<string, unknown>