-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmcp_agent.py
More file actions
344 lines (286 loc) · 12.1 KB
/
Copy pathmcp_agent.py
File metadata and controls
344 lines (286 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
import logging
from typing import Any, Dict, List, Optional
import json, os
import uuid
from datetime import datetime, timezone
import boto3
from bedrock_agentcore import BedrockAgentCoreApp
from botocore.exceptions import ClientError
from strands import Agent, tool
from strands.models import BedrockModel
from strands.multiagent import Swarm
import requests
from strands.tools.mcp.mcp_client import MCPClient
from mcp.client.streamable_http import streamablehttp_client
# =========================
# ENV & LOGGING
# =========================
AWS_REGION = os.getenv("AWS_REGION", "us-east-1")
CLIENT_ID = ""
CLIENT_SECRET = ""
TOKEN_URL = ""
MCP_GATEWAY_URL = ""
s3 = boto3.client("s3", region_name=AWS_REGION)
DDB_TABLE_NAME = os.getenv("DDB_TABLE_NAME", "ai-writer-table")
AWS_REGION = os.getenv("AWS_REGION", "us-east-1")
dynamodb = boto3.resource("dynamodb", region_name=AWS_REGION)
ddb_table = dynamodb.Table(DDB_TABLE_NAME)
app = BedrockAgentCoreApp()
@tool
def save_articles_to_dynamodb(
articles: list[dict],
author_id: str,
status: str = "IDEA",
) -> dict:
"""
Persist a batch of article ideas/outlines to DynamoDB (single-table):
- PK = USER#{author_id}
- SK = ARTICLE#{article_id}
Each article gets a fresh UUID article_id.
Returns a manifest: {count, sample, ids}
"""
created_at = now_iso()
items = []
ids = []
sample = []
for a in articles:
# Expect at least a title; outline optional but encouraged
title = (a.get("title") or "").strip()
outline = a.get("outline") or a.get("sections") or a.get("body") or ""
if not title:
# skip bad rows instead of failing the whole batch
# you can choose to raise instead
continue
article_id = str(uuid.uuid4())
ids.append(article_id)
if len(sample) < 5:
sample.append({"title": title, "article_id": article_id})
item = {
"PK": f"ARTICLE#{article_id}",
"SK": f"ARTICLE#{article_id}",
"GSI1PK": f"USER#{author_id}",
"GSI1SK": f"ARTICLE#{article_id}",
"entityType": "ARTICLE",
"articleId": article_id,
"title": title,
"outline": outline,
"status": status,
"createdAt": created_at,
"updatedAt": created_at,
"keywords": a.get("keywords") or [],
"notes": a.get("notes") or "",
"score": a.get("score"),
}
items.append(item)
if not items:
return {"error": "no valid articles to write (missing titles?)"}
try:
with ddb_table.batch_writer(overwrite_by_pkeys=["PK", "SK"]) as batch:
for it in items:
batch.put_item(Item=it)
except ClientError as e:
return {"error": f"DynamoDB batch put failed: {e.response['Error']['Message']}"}
return {"count": len(items), "sample": sample, "ids": ids}
# --- NEW: Tools for saving and retrieving keyword analysis ---
@tool
def save_keyword_report_to_dynamodb(
keyword_data: dict,
author_id: str = "anon",
report_title: str = "Untitled Keyword Report"
) -> dict:
"""
Persist a keyword analysis report (e.g., from Data4SEO) to DynamoDB.
- PK = REPORT#{report_id}
- SK = REPORT#{report_id}
- GSI1PK = USER#{author_id}
Returns a manifest: {report_id, title}
"""
report_id = str(uuid.uuid4())
created_at = now_iso()
item = {
"PK": f"REPORT#{report_id}",
"SK": f"REPORT#{report_id}",
"GSI1PK": f"USER#{author_id}",
"GSI1SK": f"REPORT#{report_id}",
"entityType": "REPORT",
"reportId": report_id,
"title": report_title,
"authorId": author_id,
"reportData": keyword_data,
"createdAt": created_at,
"updatedAt": created_at,
}
try:
ddb_table.put_item(
Item=item,
ConditionExpression="attribute_not_exists(PK)"
)
return {"report_id": report_id, "title": report_title}
except ClientError as e:
return {"error": f"DynamoDB put failed: {e.response['Error']['Message']}"}
@tool
def get_keyword_report_from_dynamodb(report_id: str) -> dict:
"""
Retrieves a specific keyword analysis report from DynamoDB using its report_id.
"""
try:
response = ddb_table.get_item(
Key={"PK": f"REPORT#{report_id}", "SK": f"REPORT#{report_id}"}
)
item = response.get("Item")
if not item:
return {"error": "Report not found."}
# Return the key data the next agent needs
return {
"report_id": item.get("reportId"),
"title": item.get("title"),
"keyword_data": item.get("reportData")
}
except ClientError as e:
return {"error": f"DynamoDB get failed: {e.response['Error']['Message']}"}
def fetch_access_token(client_id, client_secret, token_url):
response = requests.post(
token_url,
data="grant_type=client_credentials&client_id={client_id}&client_secret={client_secret}".format(
client_id=client_id, client_secret=client_secret),
headers={'Content-Type': 'application/x-www-form-urlencoded'}
)
return response.json()['access_token']
logging.getLogger("strands").setLevel(logging.INFO)
logging.basicConfig(
format="%(levelname)s | %(name)s | %(message)s",
handlers=[logging.StreamHandler()]
)
def now_iso():
return datetime.now(timezone.utc).isoformat()
reasoning_model = BedrockModel(
model_id="us.anthropic.claude-3-7-sonnet-20250219-v1:0",
temperature=0.5,
)
outline_writer_model = BedrockModel(
model_id="us.anthropic.claude-opus-4-20250514-v1:0",
temperature=0.5,
)
# =========================
# MCP transport
# =========================
def create_streamable_http_transport():
MCP_BEARER_TOKEN = fetch_access_token(CLIENT_ID, CLIENT_SECRET, TOKEN_URL)
print(f"mcp bearer token is {MCP_BEARER_TOKEN}")
if not MCP_BEARER_TOKEN or MCP_BEARER_TOKEN.startswith("<PUT_"):
raise RuntimeError("Set MCP_BEARER_TOKEN to a valid token.")
return streamablehttp_client(
MCP_GATEWAY_URL,
headers={"Authorization": f"Bearer {MCP_BEARER_TOKEN}"}
)
mcp_client = MCPClient(create_streamable_http_transport)
# =========================
# Build agents
# =========================
with mcp_client:
# Discover MCP tools (e.g., your DataForSEO SERP/Keywords endpoints)
mcp_tools = mcp_client.list_tools_sync()
# --- 1) Generate ~20 seed keywords from interests ---
generate_keyword_agent = Agent(
name="generate_keyword_agent",
description="Turns user interests into ~20 mid-tail keywords and normalized settings.",
model=reasoning_model,
system_prompt=(
"You convert a user's interests into ~20 high-quality, mid-tail keywords (2–4 words each). "
"Normalize settings too. Your input contains the original payload.\n\n"
"INPUT JSON SHAPE (from payload):\n"
"{\n"
' "interests": [string],\n'
' "language": "en", ...\n'
' "author_details": {"author_id": "..."}\n'
"}\n\n"
"OUTPUT JSON SHAPE (for next agent):\n"
"{\n"
' "language_code": "en",\n'
' "location_code": 2840,\n'
' "date_range": "2024-01-01..2024-12-31",\n'
' "keywords": ["... up to ~20 ..."]\n'
"}\n\n"
"TASK:\n"
"1. Generate the output JSON shape based on the input payload.\n"
"2. **Your FINAL action MUST be to call `use_agent`** to handoff to the next agent.\n"
"3. Call `use_agent` with:\n"
" - agent_name='keywords_volume_agent'\n"
" - message='Generated keywords, please fetch volumes.'\n"
" - context: {\n"
" \"keyword_settings\": <The JSON you just generated>,\n"
" \"original_payload\": <The full original payload you received>\n"
" }"
),
)
# --- 2) Fetch volumes via DataForSEO (MCP tools) ---
# This agent will call your MCP tools. Keep its prompt laser-focused on tool use + shaping outputs.
all_tools = [*mcp_tools,save_keyword_report_to_dynamodb]
keywords_volume_agent = Agent(
name="keywords_volume_agent",
description="Fetch metrics via Data4SEO MCP, store to file, return only a manifest.",
model=reasoning_model,
tools=all_tools,
system_prompt=(
"Your INPUT is a JSON context from the previous agent(generate_keyword_agent). It contains 'keyword_settings' and 'original_payload'.\n\n"
"TASK:\n"
"1. Extract 'keywords', 'language_code', etc., from 'keyword_settings'.\n"
"2. Call the DataForSEO MCP keyword volume search tool to get metrics for the keywords.\n"
"3. Format the tool's raw output into the structured JSON report (e.g., {'task_id': ..., 'results': [...]}).\n"
"4. Extract 'author_id' from 'original_payload.author_details'. Default to 'anon' if missing.\n"
"5. Call `save_keyword_report_to_dynamodb` with the JSON report as `keyword_data` and the 'author_id'.\n"
"6. Generate a human-readable markdown 'summary' of the results.\n"
"7. **Your FINAL action MUST be to call `use_agent`** to handoff to the outline writer.\n"
"8. Call `use_agent` with:\n"
" - agent_name='outline_writer_agent'\n"
" - message='Keyword report is ready, please write outlines.'\n"
" - context: {\n"
" \"report_id\": <The ID from save_keyword_report_to_dynamodb tool call>,\n"
" \"summary\": <Your markdown summary>,\n"
" \"original_payload\": <The original_payload you received>\n"
" }"
),
)
# --- 4) Produce titles + outlines for the top picks ---
outline_writer_agent = Agent(
name="outline_writer_agent",
description="Retrieves a keyword report from DynamoDB, generates titles/outlines, and saves them.",
model=outline_writer_model,
tools=[save_articles_to_dynamodb,get_keyword_report_from_dynamodb],
system_prompt=(
"You are an SEO content strategist. Your INPUT is a JSON context from the previous agent.\n"
"The input context contains 'report_id' and 'original_payload'.\n\n"
"TASK:\n"
"1. Extract the `report_id` from your input context.\n"
"2. **Your FIRST action MUST be to call `get_keyword_report_from_dynamodb`** using this `report_id`.\n"
"3. Analyze the 'keyword_data' from the tool's response.\n"
"4. Generate ~10 SEO-friendly article titles and concise outlines (H2s/H3s) based on the data.\n"
"5. Extract `author_id` from 'original_payload.author_details'. Default to 'anon' if missing.\n"
"6. **Your FINAL action MUST be to call `save_articles_to_dynamodb`** with your generated articles and the 'author_id'.\n"
"7. Return ONLY the manifest (count, sample, ids) from the tool. This is the final output of the swarm."
),
)
@app.entrypoint
def invoke(payload):
swarm_agent = Swarm(
nodes=[generate_keyword_agent,keywords_volume_agent,outline_writer_agent],
entry_point=generate_keyword_agent,
max_handoffs=10,
max_iterations=15
)
initial_payload: Dict[str, Any] = {
"interests": ["agentic applications", "edtech", "knowledge bases", "poetry", "deep research", "ai"],
"language": "English",
"location": "United States",
"date_range": "1y",
"author_details": {
"author_id": "6d2a9e9f-e1fb-43e0-b8b2-492d54e074e1"
}
}
response = swarm_agent(
"Generate keyword strategy and outlines using this payload. "
"Return STRICT JSON at every step.\n" + json.dumps(initial_payload)
)
return response
if __name__ == "__main__":
app.run()