MCPcopy
hub / github.com/shareAI-lab/learn-claude-code / agent_loop

Function agent_loop

s19_mcp_plugin/code.py:962–995  ·  view source on GitHub ↗
(messages: list, context: dict)

Source from the content-addressed store, hash-verified

960# ── Agent Loop (s19: dynamic tool pool, no prompt cache) ──
961
962def agent_loop(messages: list, context: dict):
963 tools, handlers = assemble_tool_pool()
964 system = assemble_system_prompt(context)
965 while True:
966 try:
967 response = client.messages.create(
968 model=MODEL, system=system, messages=messages,
969 tools=tools, max_tokens=8000)
970 except Exception as e:
971 messages.append({"role": "assistant", "content": [
972 {"type": "text", "text": f"[Error] {type(e).__name__}: {e}"}]})
973 return
974
975 messages.append({"role": "assistant", "content": response.content})
976 if response.stop_reason != "tool_use":
977 return
978
979 results = []
980 for block in response.content:
981 if block.type != "tool_use":
982 continue
983 print(f"\033[36m> {block.name}\033[0m")
984 handler = handlers.get(block.name)
985 output = handler(**block.input) if handler else "Unknown"
986 print(str(output)[:300])
987 results.append({"type": "tool_result",
988 "tool_use_id": block.id, "content": output})
989 messages.append({"role": "user", "content": results})
990
991 if any(b.name == "connect_mcp" for b in response.content
992 if b.type == "tool_use"):
993 tools, handlers = assemble_tool_pool()
994 context = update_context(context, messages)
995 system = assemble_system_prompt(context)
996
997
998if __name__ == "__main__":

Callers 1

code.pyFile · 0.70

Calls 5

assemble_tool_poolFunction · 0.70
assemble_system_promptFunction · 0.70
update_contextFunction · 0.70
createMethod · 0.45
getMethod · 0.45

Tested by

no test coverage detected