从您的 AgentCore 网关接收日志消息
MCP 服务器目标可以在工具执行期间使用该notifications/message方法向客户端发送日志消息。这些消息提供服务器正在执行的操作的实时可见性,这对于调试、审计和监控工具行为非常有用。 AgentCore Gateway 将这些来自 MCP 服务器目标的日志通知作为 Server-Sent 事件 (SSE) 区块转发到您的客户端。
先决条件
要从您的网关接收日志消息,请执行以下操作:
-
启用响应流-在打开的连接期间,日志消息以 SSE 区块的形式传送。true在streamingConfiguration.enableResponseStreaming您的网关中设置为protocolConfiguration.mcp。
-
MCP 服务器目标类型-日志消息源自 MCP 服务器目标。
-
客户端发送Accept: text/event-stream标头-客户端必须请求 SSE 响应才能接收流媒体事件。
日志级别
MCP 按严重性递增的顺序定义以下日志级别:
| 级别 |
说明 |
|
debug
|
用于故障排除的详细诊断信息。
|
|
info
|
有关正常操作的一般信息性消息。
|
|
notice
|
正常但重要的事件。
|
|
warning
|
不会阻止操作的潜在有害情况。
|
|
error
|
阻止特定操作的错误条件。
|
|
critical
|
需要立即关注的危急情况。
|
|
alert
|
必须立即采取行动。
|
|
emergency
|
系统无法使用。
|
记录消息的工作原理
当 MCP 服务器目标notifications/message在工具执行期间发出时,网关会将其作为 SSE 事件转发给客户端。每条日志消息包括:
-
level— 消息的严重性级别。
-
logger— 标识源组件的可选名称。
-
data— 日志内容(字符串或结构化对象)。
日志消息是信息性的,不需要客户端的响应。它们与其他 SSE 事件(例如进度通知和最终工具结果)一起交付。
代码示例
例
- curl
-
-
调用工具并在 SSE 直播中接收日志消息:
curl -N -X POST \
https://mygateway-abcdefghij.gateway.bedrock-agentcore.us-west-2.amazonaws.com/mcp \
-H "Content-Type: application/json" \
-H "Accept: text/event-stream" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-d '{
"jsonrpc": "2.0",
"id": "tool-call-1",
"method": "tools/call",
"params": {
"name": "deployService",
"arguments": {
"serviceName": "my-api",
"environment": "staging"
}
}
}'
网关返回带有日志消息的 SSE 流,后面是最终结果:
event: message
data: {"jsonrpc":"2.0","method":"notifications/message","params":{"level":"info","logger":"deploy-service","data":"Starting deployment of my-api to staging"}}
event: message
data: {"jsonrpc":"2.0","method":"notifications/message","params":{"level":"info","logger":"deploy-service","data":"Building container image..."}}
event: message
data: {"jsonrpc":"2.0","method":"notifications/message","params":{"level":"warning","logger":"deploy-service","data":"Deprecated configuration detected in service manifest"}}
event: message
data: {"jsonrpc":"2.0","method":"notifications/message","params":{"level":"info","logger":"deploy-service","data":"Deployment complete"}}
event: message
data: {"jsonrpc":"2.0","id":"tool-call-1","result":{"content":[{"type":"text","text":"Successfully deployed my-api to staging environment."}]}}
- Python requests package
-
-
import requests
import json
import sseclient
gateway_url = "https://mygateway-abcdefghij.gateway.bedrock-agentcore.us-west-2.amazonaws.com/mcp"
headers = {
"Content-Type": "application/json",
"Accept": "text/event-stream",
"Authorization": "Bearer YOUR_ACCESS_TOKEN"
}
# Call tool (streaming response)
response = requests.post(gateway_url, headers=headers, json={
"jsonrpc": "2.0",
"id": "tool-call-1",
"method": "tools/call",
"params": {
"name": "deployService",
"arguments": {"serviceName": "my-api", "environment": "staging"}
}
}, stream=True)
# Process SSE events
client = sseclient.SSEClient(response)
for event in client.events():
data = json.loads(event.data)
if data.get("method") == "notifications/message":
params = data["params"]
print(f"[{params['level'].upper()}] {params.get('logger', '')}: {params['data']}")
elif "result" in data:
print(f"Tool result: {data['result']}")
break
- MCP Client
-
-
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client
import asyncio
async def log_handler(level, logger, data):
"""Handle log messages from the server."""
print(f"[{level.upper()}] {logger or 'server'}: {data}")
async def use_logging(url, token):
headers = {"Authorization": f"Bearer {token}"}
async with streamablehttp_client(url=url, headers=headers) as (
read_stream, write_stream, _
):
async with ClientSession(
read_stream, write_stream,
logging_handler=log_handler
) as session:
await session.initialize()
# Call tool - log messages handled by callback
result = await session.call_tool(
name="deployService",
arguments={"serviceName": "my-api", "environment": "staging"}
)
print(f"Tool result: {result}")
return result
asyncio.run(use_logging(
url="https://mygateway-abcdefghij.gateway.bedrock-agentcore.us-west-2.amazonaws.com/mcp",
token="YOUR_ACCESS_TOKEN"
))
- Strands MCP Client
-
-
from mcp.client.streamable_http import streamablehttp_client
from strands import Agent
from strands.tools.mcp import MCPClient
mcp_url = "https://mygateway-abcdefghij.gateway.bedrock-agentcore.us-west-2.amazonaws.com/mcp"
access_token = "YOUR_ACCESS_TOKEN"
mcp_client = MCPClient(
lambda: streamablehttp_client(
mcp_url, headers={"Authorization": f"Bearer {access_token}"}
)
)
# Strands handles streaming and log messages automatically
with mcp_client:
agent = Agent(tools=mcp_client.list_tools_sync())
response = agent("Deploy my-api to staging")
print(response)