मुख्य सामग्री पर जाएं

सैम्पलिंग

सर्वर से आने वाले LLM completion अनुरोधों को संभालें
MCP सर्वर tool निष्पादन के दौरान Client से LLM completions का अनुरोध कर सकते हैं। इससे सर्वर AI reasoning को Client को सौंप सकते हैं, जो नियंत्रित करता है कि कौन‑सा model उपयोग किया जाए।

Handler

सैंपलिंग को सपोर्ट करने के लिए, कनेक्ट करते समय एक सैंपलिंग हैंडलर रजिस्टर करें। यह हैंडलर सर्वर की रिक्वेस्ट (CreateMessageRequestParams) प्राप्त करता है और इसे निम्न में से किसी एक को रिटर्न करना चाहिए:
  • CreateMessageResult (सफलता), या
  • ErrorData (विफलता)
यहाँ Anthropic का उपयोग करते हुए एक पूर्ण उदाहरण है:
from anthropic import AsyncAnthropic
from dedalus_mcp import types

anthropic = AsyncAnthropic()

async def sampling_handler(
    _ctx: object,
    params: types.CreateMessageRequestParams,
) -> types.CreateMessageResult | types.ErrorData:
    try:
        messages = [{"role": m.role, "content": m.content.text} for m in params.messages]

        resp = await anthropic.messages.create(
            model="claude-sonnet-4-20250514",
            messages=messages,
            max_tokens=params.maxTokens,
        )

        return types.CreateMessageResult(
            model=resp.model,
            role="assistant",
            content=types.TextContent(type="text", text=resp.content[0].text),
            stopReason="end_turn",
        )
    except Exception as e:
        return types.ErrorData(code=types.INTERNAL_ERROR, message=str(e))

उपयोग

कनेक्ट करते समय ClientCapabilitiesConfig में handler को पास करके sampling सक्षम करें:
capabilities = ClientCapabilitiesConfig(sampling=sampling_handler)

async with open_connection(
    url="http://127.0.0.1:8000/mcp",
    capabilities=capabilities,
) as client:
    # यदि सर्वर इस tool रन के दौरान sampling/createMessage को कॉल करता है,
    # तो आपका sampling_handler invoke किया जाएगा।
    result = await client.call_tool("analyze", {"data": "..."})

त्रुटि प्रबंधन

जब आपके handler के अंदर कुछ गलत हो जाए, तो ErrorData लौटाएँ (raise न करें)। सर्वर को यह उसके sampling अनुरोध के लिए मॉडल कॉन्टेक्स्ट प्रोटोकॉल (MCP) त्रुटि प्रतिक्रिया के रूप में प्राप्त होगा।
from dedalus_mcp import types

async def sampling_handler(context: object, params: types.CreateMessageRequestParams):
    try:
        # ... LLM को कॉल करें ...
        return types.CreateMessageResult(
            model="claude-3-5-sonnet-20241022",
            role="assistant",
            content=types.TextContent(type="text", text="ok"),
            stopReason="end_turn",
        )
    except Exception as e:
        return types.ErrorData(code=types.INTERNAL_ERROR, message=str(e))