선택 사항: Greengrass로 주사위 굴리기
모듈 4에서 배포한 던전을 유지하세요. 파괴하기 전에 Story Agent에 주사위 디바이스를 제공하세요:
“자물쇠를 따려고 합니다. 성공 여부를 확인하기 위해 d20을 굴려주세요.”
에이전트는 roll-dice를 호출합니다. Greengrass 코어의 Python 컴포넌트가
주사위 굴림을 생성하고, MCP 도구가 해당 디바이스 결과를 에이전트에 반환합니다. 응답은
“d20: 17”이라고 말하고 결과를 설명할 수 있습니다.
이 선택적 경로는 소프트웨어 주사위 시뮬레이터가 있는 EC2 코어를 사용합니다. 나중에 난수 함수를 물리적 주사위 트레이의 입력으로 교체할 수 있습니다. 독립형 Greengrass 튜토리얼은 빈 워크스페이스에서 컴포넌트 생성을 배우는 별도의 방법으로 남아 있습니다.
추가할 내용
섹션 제목: “추가할 내용”클라우드 섀도우는 하나의 대기 중인 요청과 가장 최근 결과를 보유합니다. 도구는 최대 12초 동안 대기하며, 대체 굴림을 생성하지 않습니다. 버전 확인은 동시 호출자가 활성 요청을 교체하는 것을 방지합니다. 디바이스는 게시하기 전에 마지막 결과를 저장하므로 MQTT 재전송 및 컴포넌트 재시작이 동일한 요청을 다시 굴리지 않습니다.
이 샌드박스는 플레이어 간에 하나의 주사위 디바이스를 공유합니다. 사용 중인 디바이스는 오류를 반환합니다. 플릿 전체 큐를 추가하거나 개인 디바이스를 Cognito 사용자와 연결하지 않습니다. 이는 멀티플레이어 제품을 위한 별도의 확장입니다.
1. 던전을 해체하지 않고 코어 프로비저닝
섹션 제목: “1. 던전을 해체하지 않고 코어 프로비저닝”배포된 던전과 동일한 AWS 계정 및 리전을 사용하세요. 프로필을 명시적으로 설정하고, 디바이스 리소스에 새 접두사를 사용하세요:
export TUTORIAL_AWS_PROFILE=<your-dungeon-profile>export TUTORIAL_AWS_REGION=<your-dungeon-region>export TUTORIAL_PREFIX=gg-dungeon-dice임시 설치 프로그램 정책 제거를 포함하여 던전 워크스페이스에서
코어 디바이스 프로비저닝을 따르세요.
해당 페이지는 인스턴스를 생성하고 .greengrass-tutorial.env를 작성합니다.
다른 Nx 워크스페이스를 생성하거나 독립형 하트비트 모듈을 실행하지 마세요.
설정 스크립트의 기존 기본값은 변경되지 않습니다.
source .greengrass-tutorial.envexport DICE_IOT_ENDPOINT=$(aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" \ iot describe-endpoint --endpoint-type iot:Data-ATS --query endpointAddress --output text)도구를 활성화하기 전에 새 디바이스의 명명된 섀도우를 한 번 초기화하세요. 활성 주사위 요청이 있는 디바이스에 대해 이 재설정을 실행하지 마세요:
aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" \ iot-data update-thing-shadow --endpoint-url "https://${DICE_IOT_ENDPOINT}" \ --thing-name "$TUTORIAL_THING_NAME" --shadow-name dungeon-dice \ --cli-binary-format raw-in-base64-out \ --payload '{"state":{"desired":{"command":null},"reported":{"command":null,"result":null}}}' \ /tmp/dungeon-dice-shadow.jsonEC2 워크스루는 x86_64 Linux를 사용합니다. 64비트 Linux를 실행하는 Raspberry Pi는
대신 linux-arm64를 사용합니다. 생성된 레시피와 네이티브 종속성 모두
해당 아키텍처를 대상으로 해야 합니다. 하드웨어 지원을 참조하세요.
ESP32는 게이트웨이에 센서 입력을 제공할 수 있지만 이 Python 컴포넌트를 실행할 수 없습니다.
2. 주사위 컴포넌트 생성
섹션 제목: “2. 주사위 컴포넌트 생성”디바이스 아티팩트가 Story Agent의 클라우드 종속성을 포함하지 않도록 별도의 Python 호스트를 생성하세요:
이 제너레이터 실행@aws/nx-plugin:py#project
pnpm nx g @aws/nx-plugin:py#project --name=edge --no-interactive yarn nx g @aws/nx-plugin:py#project --name=edge --no-interactive npx nx g @aws/nx-plugin:py#project --name=edge --no-interactive bunx nx g @aws/nx-plugin:py#project --name=edge --no-interactive- 설치 Nx Console VSCode Plugin 아직 설치하지 않았다면
- VSCode에서 Nx 콘솔 열기
- 클릭
Generate (UI)"Common Nx Commands" 섹션에서 - 검색
@aws/nx-plugin - py#project - 필수 매개변수 입력
- name: edge
- 클릭
Generate
이 단계의 옵션1
필수
이 제너레이터 실행@aws/nx-plugin:greengrass#component
pnpm nx g @aws/nx-plugin:greengrass#component --project=edge --name=dice --platform=linux-amd64 --infra=component-version --iac=cdk --language=python --componentName=com.example.DungeonDice --componentVersion=NEXT_PATCH --ipc=true --no-interactive yarn nx g @aws/nx-plugin:greengrass#component --project=edge --name=dice --platform=linux-amd64 --infra=component-version --iac=cdk --language=python --componentName=com.example.DungeonDice --componentVersion=NEXT_PATCH --ipc=true --no-interactive npx nx g @aws/nx-plugin:greengrass#component --project=edge --name=dice --platform=linux-amd64 --infra=component-version --iac=cdk --language=python --componentName=com.example.DungeonDice --componentVersion=NEXT_PATCH --ipc=true --no-interactive bunx nx g @aws/nx-plugin:greengrass#component --project=edge --name=dice --platform=linux-amd64 --infra=component-version --iac=cdk --language=python --componentName=com.example.DungeonDice --componentVersion=NEXT_PATCH --ipc=true --no-interactive- 설치 Nx Console VSCode Plugin 아직 설치하지 않았다면
- VSCode에서 Nx 콘솔 열기
- 클릭
Generate (UI)"Common Nx Commands" 섹션에서 - 검색
@aws/nx-plugin - greengrass#component - 필수 매개변수 입력
- project: edge
- name: dice
- language: python
- componentName: com.example.DungeonDice
- componentVersion: NEXT_PATCH
- platform: linux-amd64
- ipc: true
- infra: component-version
- iac: cdk
- 클릭
Generate
이 단계의 옵션9
필수
필수
packages/edge/greengrass/dice/main.py를 교체하세요:
import argparseimport jsonimport loggingimport osimport queueimport secretsimport timeimport uuidfrom pathlib import Pathfrom typing import TypedDict
SIDES = (4, 6, 8, 10, 12, 20)logger = logging.getLogger("com.example.DungeonDice")
class DiceResult(TypedDict): requestId: str sides: int value: int rolledAt: int
class SavedRoll(TypedDict): version: int result: DiceResult
class Dice: def __init__(self, state_path: Path): self.state_path = state_path self.last: SavedRoll | None = ( json.loads(state_path.read_text()) if state_path.exists() else None )
def roll(self, command: dict, version: int, now: int) -> DiceResult | None: try: uuid.UUID(command["requestId"]) sides = command["sides"] expires_at = command["expiresAt"] if type(sides) is not int or sides not in SIDES: return None if type(expires_at) is not int or expires_at <= now: return None if type(version) is not int or version < 1: return None except (KeyError, TypeError, ValueError, AttributeError): return None if self.last: if command["requestId"] == self.last["result"]["requestId"]: return self.last["result"] if sides == self.last["result"]["sides"] else None if version <= self.last["version"]: logger.warning( "Ignoring stale shadow version %s; last processed version was %s", version, self.last["version"], ) return None result: DiceResult = { "requestId": command["requestId"], "sides": sides, "value": secrets.randbelow(sides) + 1, "rolledAt": now, } saved: SavedRoll = {"version": version, "result": result} temporary = self.state_path.with_suffix(".tmp") with temporary.open("w") as stream: json.dump(saved, stream) stream.flush() os.fsync(stream.fileno()) os.replace(temporary, self.state_path) self.last = saved logger.info("Rolled d%s = %s, request %s", sides, result["value"], result["requestId"]) return result
def main() -> None: from awsiot.greengrasscoreipc.clientv2 import GreengrassCoreIPCClientV2
parser = argparse.ArgumentParser() parser.add_argument("--thing-name", required=True) args = parser.parse_args() logging.basicConfig(level=logging.INFO) client = GreengrassCoreIPCClientV2() base = f"$aws/things/{args.thing_name}/shadow/name/dungeon-dice" events = queue.Queue() dice = Dice(Path("dice-result.json")) subscriptions = []
def publish(suffix: str, payload: dict) -> None: client.publish_to_iot_core( topic_name=f"{base}/{suffix}", qos="1", payload=json.dumps(payload).encode(), )
def on_event(event) -> None: events.put(event.message)
for suffix in ("get/accepted", "update/delta", "update/rejected"): _, operation = client.subscribe_to_iot_core( topic_name=f"{base}/{suffix}", qos="1", on_stream_event=on_event ) subscriptions.append(operation) next_read = 0.0 try: while True: try: if time.monotonic() >= next_read: publish("get", {}) next_read = time.monotonic() + 15 message = events.get(timeout=1) document = json.loads(message.payload) if message.topic_name.endswith("/update/rejected"): logger.warning("Shadow update rejected: %s", document.get("code")) next_read = 0 continue state = document.get("state", {}) if message.topic_name.endswith("/update/delta"): command = state.get("command") else: command = state.get("desired", {}).get("command") reported = state.get("reported", {}).get("result", {}) if command and reported.get("requestId") == command.get("requestId"): continue if not isinstance(command, dict): continue version = document.get("version") result = dice.roll(command, version, int(time.time())) if result: publish("update", { "version": version, "state": {"reported": {"command": command, "result": result}}, }) except queue.Empty: continue except Exception: logger.exception("Dice exchange failed; will read the shadow again") next_read = time.monotonic() + 5 finally: for operation in subscriptions: operation.close() client.close()
if __name__ == "__main__": main()packages/edge/greengrass/dice/recipe.yaml을 교체하세요:
RecipeFormatVersion: '2020-01-25'ComponentName: com.example.DungeonDiceComponentVersion: NEXT_PATCHComponentDescription: Dice rolls requested by the Dungeon Adventure Story Agent.ComponentPublisher: dungeon-adventureComponentConfiguration: DefaultConfiguration: thingName: REPLACE_WITH_CORE_THING_NAME accessControl: aws.greengrass.ipc.mqttproxy: com.example.DungeonDice:mqttproxy:1: policyDescription: Exchange dice requests and results through the named cloud shadow. operations: - aws.greengrass#PublishToIoTCore - aws.greengrass#SubscribeToIoTCore resources: - $aws/things/REPLACE_WITH_CORE_THING_NAME/shadow/name/dungeon-dice/get - $aws/things/REPLACE_WITH_CORE_THING_NAME/shadow/name/dungeon-dice/get/accepted - $aws/things/REPLACE_WITH_CORE_THING_NAME/shadow/name/dungeon-dice/update - $aws/things/REPLACE_WITH_CORE_THING_NAME/shadow/name/dungeon-dice/update/delta - $aws/things/REPLACE_WITH_CORE_THING_NAME/shadow/name/dungeon-dice/update/rejectedManifests: - Platform: os: linux architecture: amd64 Artifacts: - Uri: s3://BUCKET_NAME/COMPONENT_NAME/COMPONENT_VERSION/dice.zip Unarchive: ZIP Lifecycle: Run: python3.14 {artifacts:decompressedPath}/dice/main.py --thing-name "{configuration:/thingName}"모든 REPLACE_WITH_CORE_THING_NAME을 TUTORIAL_THING_NAME 값으로 교체하세요.
레시피의 IPC 권한은 이 디바이스의 주사위 섀도우 주제만 지정합니다.
Python은 읽기 전용 아티팩트 디렉터리 외부의 컴포넌트 쓰기 가능 작업 디렉터리에
dice-result.json을 작성합니다.
packages/edge/tests/greengrass/test_dice.py를 교체하세요:
import importlib.utilimport osimport tempfileimport unittestimport uuidfrom importlib.machinery import SourceFileLoaderfrom pathlib import Pathfrom unittest.mock import patch
MODULE_PATH = Path(os.environ.get( "DICE_MODULE_PATH", Path(__file__).parents[2] / "greengrass" / "dice" / "main.py",))loader = SourceFileLoader("dungeon_dice", str(MODULE_PATH))spec = importlib.util.spec_from_loader(loader.name, loader)assert spec is not Nonedice_module = importlib.util.module_from_spec(spec)loader.exec_module(dice_module)
class TestDice(unittest.TestCase): def setUp(self): self.directory = tempfile.TemporaryDirectory() self.addCleanup(self.directory.cleanup) self.path = Path(self.directory.name) / "dice-result.json" self.dice = dice_module.Dice(self.path) self.command = {"requestId": str(uuid.uuid4()), "sides": 20, "expiresAt": 120}
def test_roll_uses_device_randomness_and_valid_range(self): with patch.object(dice_module.secrets, "randbelow", return_value=16) as random: result = self.dice.roll(self.command, 1, 100) self.assertEqual(result["value"], 17) self.assertEqual(result["requestId"], self.command["requestId"]) random.assert_called_once_with(20)
def test_duplicate_and_restart_reuse_the_persisted_result(self): first = self.dice.roll(self.command, 1, 100) with patch.object(dice_module.secrets, "randbelow", side_effect=AssertionError("rerolled")): self.assertEqual(self.dice.roll(self.command, 1, 101), first) self.assertEqual(dice_module.Dice(self.path).roll(self.command, 2, 102), first)
def test_expired_or_invalid_requests_do_not_roll(self): for command in ( {**self.command, "expiresAt": 100}, {**self.command, "sides": 7}, {**self.command, "sides": True}, {**self.command, "requestId": "invalid"}, {}, ): with self.subTest(command=command): self.assertIsNone(self.dice.roll(command, 1, 100)) self.assertFalse(self.path.exists())
def test_stale_delivery_cannot_roll_after_a_newer_request(self): self.dice.roll(self.command, 5, 100) stale = {**self.command, "requestId": str(uuid.uuid4())} self.assertIsNone(self.dice.roll(stale, 4, 100))
def test_stale_shadow_version_logs_after_shadow_reset(self): self.dice.roll(self.command, 5, 100) reset_shadow_command = {**self.command, "requestId": str(uuid.uuid4())} with self.assertLogs(dice_module.logger, level="WARNING") as warning: self.assertIsNone(self.dice.roll(reset_shadow_command, 1, 100)) self.assertIn("Ignoring stale shadow version 1", warning.output[0])
def test_request_id_cannot_be_reused_with_different_sides(self): self.dice.roll(self.command, 1, 100) self.assertIsNone(self.dice.roll({**self.command, "sides": 6}, 2, 100))
def test_failed_persistence_does_not_publish_a_result(self): with ( patch.object(dice_module.os, "replace", side_effect=OSError("disk full")), self.assertRaises(OSError), ): self.dice.roll(self.command, 1, 100) self.assertIsNone(self.dice.last)
if __name__ == "__main__": unittest.main()이러한 테스트는 유효한 굴림, 중복, 재시작 복구, 오래된 요청, 만료 및 지속성 실패를 실행합니다. 컴포넌트가 이제 다른 동작을 구현하므로 기본 생성기의 하트비트 테스트가 교체됩니다.
3. 에이전트의 주사위 도구 추가
섹션 제목: “3. 에이전트의 주사위 도구 추가”Inventory MCP 프로젝트에 IoT 데이터 플레인 클라이언트를 추가하세요:
pnpm add @aws-sdk/client-iot-data-plane@3.1169.0 --filter inventoryyarn workspace @dungeon-adventure/inventory add @aws-sdk/client-iot-data-plane@3.1169.0npm install --legacy-peer-deps @aws-sdk/client-iot-data-plane@3.1169.0 -w packages/inventorybun add @aws-sdk/client-iot-data-plane@3.1169.0 --cwd packages/inventorypackages/inventory/src/mcp-server/roll-dice.ts를 생성하세요:
import { randomUUID } from 'node:crypto';import { setTimeout } from 'node:timers/promises';
export const diceSides = [4, 6, 8, 10, 12, 20] as const;
export interface DiceRequest { requestId: string; sides: number; expiresAt: number;}
export interface DiceResult { requestId: string; sides: number; value: number; rolledAt: number;}
export interface DiceShadow { version: number; state?: { desired?: { command?: DiceRequest | null }; reported?: { result?: DiceResult | null }; };}
export interface ShadowUpdate { version: number; state: { desired: { command: DiceRequest | null }; reported?: { command: null }; };}
export interface DiceTransport { read(signal: AbortSignal): Promise<DiceShadow>; update(update: ShadowUpdate, signal: AbortSignal): Promise<void>;}
export function createDiceRoller( transport: DiceTransport, clock = Date.now, pause = (signal: AbortSignal) => setTimeout(500, undefined, { signal }),) { return async (sides: number): Promise<DiceResult> => { if (!diceSides.some((allowed) => sides === allowed)) { throw new Error('Choose d4, d6, d8, d10, d12 or d20.'); } const signal = AbortSignal.timeout(12_000); const deadline = clock() + 12_000; const current = await transport.read(signal); if (!Number.isInteger(current.version)) { throw new Error('The dice shadow has no version. Initialize it before playing.'); } const active = current.state?.desired?.command; if (active && active.expiresAt * 1000 > clock()) { throw new Error('The shared dice device is busy. Wait before trying again.'); } const request: DiceRequest = { requestId: randomUUID(), sides, expiresAt: Math.ceil(deadline / 1000) + 5, }; // The version makes simultaneous callers compete for a single request slot. await transport.update({ version: current.version, state: { desired: { command: request } }, }, signal);
while (clock() < deadline) { const shadow = await transport.read(signal); const result = shadow.state?.reported?.result; if (result?.requestId === request.requestId) { if ( result.sides !== sides || !Number.isInteger(result.value) || result.value < 1 || result.value > sides || !Number.isInteger(result.rolledAt) ) { throw new Error('The device returned an invalid dice result.'); } // Release only this request. A late update must not clear a newer one. if (shadow.state?.desired?.command?.requestId === request.requestId) { try { await transport.update({ version: shadow.version, state: { desired: { command: null }, reported: { command: null } }, }, signal); } catch (error) { console.warn('Dice result received; request slot will expire:', error); } } return result; } if (shadow.state?.desired?.command?.requestId !== request.requestId) { throw new Error('The dice request was replaced. No roll result is available.'); } await pause(signal); } throw new Error('The dice device did not respond in time. No roll was fabricated.'); };}packages/inventory/src/mcp-server/register-dice.ts를 생성하세요:
import { GetThingShadowCommand, IoTDataPlaneClient, UpdateThingShadowCommand,} from '@aws-sdk/client-iot-data-plane';import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { z } from 'zod';import { createDiceRoller, diceSides, type DiceShadow } from './roll-dice.js';
export function registerDiceTool(server: McpServer) { server.registerTool('roll-dice', { description: 'Ask the physical or simulated Greengrass dice device for a roll. Use its returned value; never invent a result when this tool fails.', inputSchema: { sides: z.number().int().refine((value) => diceSides.some((sides) => value === sides), { message: 'Choose 4, 6, 8, 10, 12 or 20 sides.', }), }, }, async ({ sides }) => { const thingName = process.env.DICE_THING_NAME; const endpoint = process.env.DICE_IOT_ENDPOINT; const region = process.env.DICE_AWS_REGION; if (!thingName || !endpoint || !region) { return { isError: true, content: [{ type: 'text' as const, text: 'The dice tool is not configured. Set DICE_THING_NAME, DICE_IOT_ENDPOINT and DICE_AWS_REGION before requesting a roll. Tell the player that no roll is available. Do not invent a result.' }], }; } try { const client = new IoTDataPlaneClient({ region, endpoint: `https://${endpoint}`, maxAttempts: 2, }); const input = { thingName, shadowName: 'dungeon-dice' }; const roll = createDiceRoller({ async read(signal) { const response = await client.send(new GetThingShadowCommand(input), { abortSignal: signal }); if (!response.payload) throw new Error('The dice shadow returned an empty response.'); return JSON.parse(new TextDecoder().decode(response.payload)) as DiceShadow; }, async update(update, signal) { await client.send(new UpdateThingShadowCommand({ ...input, payload: new TextEncoder().encode(JSON.stringify(update)), }), { abortSignal: signal }); }, }); const result = await roll(sides); return { content: [{ type: 'text' as const, text: JSON.stringify({ ...result, device: thingName }) }] }; } catch (error) { console.error('Greengrass dice request failed:', error); return { isError: true, content: [{ type: 'text' as const, text: 'The dice device is busy or unavailable, or its result was invalid. Tell the player that no roll is available and ask them to retry. Do not invent a result.' }], }; } });}packages/inventory/src/mcp-server/server.ts를 업데이트하세요:
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import z from 'zod';import { createInventoryEntity } from '@dungeon-adventure/dungeon-db';import { registerDiceTool } from './register-dice.js';
/** * Create the MCP Server */export const createServer = async () => { const server = new McpServer({ name: 'inventory-mcp-server', version: '1.0.0', });
server.registerTool( 'list-inventory-items', { description: "List items in the player's inventory. Leave cursor blank unless you are requesting subsequent pages", inputSchema: { playerName: z.string(), cursor: z.string().optional(), }, }, async ({ playerName }) => { const inventory = await createInventoryEntity(); const results = await inventory.query .primary({ playerName, }) .go();
return { content: [{ type: 'text' as const, text: JSON.stringify(results) }], }; }, );
server.registerTool( 'add-to-inventory', { description: "Add an item to the player's inventory. Quantity defaults to 1 if omitted.", inputSchema: { playerName: z.string(), itemName: z.string(), emoji: z.string(), quantity: z.number().optional().default(1), }, }, async ({ playerName, itemName, emoji, quantity = 1 }) => { const inventory = await createInventoryEntity(); await inventory .put({ playerName, itemName, quantity, emoji, }) .go();
return { content: [ { type: 'text' as const, text: `Added ${itemName} (x${quantity}) to inventory`, }, ], }; }, );
server.registerTool( 'remove-from-inventory', { description: "Remove an item from the player's inventory. If quantity is omitted, all items are removed.", inputSchema: { playerName: z.string(), itemName: z.string(), quantity: z.number().optional(), }, }, async ({ playerName, itemName, quantity }) => { const inventory = await createInventoryEntity();
// If quantity is omitted, remove the entire item if (quantity === undefined) { try { await inventory.delete({ playerName, itemName }).go(); return { content: [ { type: 'text' as const, text: `${itemName} removed from inventory.` }, ], }; } catch { return { content: [ { type: 'text' as const, text: `${itemName} not found in inventory` }, ], }; } }
// If quantity is specified, fetch current quantity and update const item = await inventory.get({ playerName, itemName }).go();
if (!item.data) { return { content: [ { type: 'text' as const, text: `${itemName} not found in inventory` }, ], }; }
const newQuantity = item.data.quantity - quantity;
if (newQuantity <= 0) { await inventory.delete({ playerName, itemName }).go(); return { content: [ { type: 'text' as const, text: `${itemName} removed from inventory.` }, ], }; }
await inventory .put({ playerName, itemName, quantity: newQuantity, emoji: item.data.emoji, }) .go();
return { content: [ { type: 'text' as const, text: `Removed ${itemName} (x${quantity}) from inventory. ${newQuantity} remaining.`, }, ], }; }, );
registerDiceTool(server); return server;};세 가지 인벤토리 도구를 모두 유지하세요. 생성된 Story Agent 연결은 이미
이 서버에서 도구를 검색하므로 roll-dice도 검색합니다.
도구는 주사위 크기만 허용합니다. 디바이스 ID와 엔드포인트는
서버 구성에서 가져오며, 모델은 다른 디바이스나 MQTT 주제를 선택할 수 없습니다.
로컬 개발 중에는 DICE_* 환경 변수 없이도 인벤토리 도구를 사용할 수 있습니다.
DICE_THING_NAME, DICE_IOT_ENDPOINT 및 DICE_AWS_REGION이 설정될 때까지
roll-dice를 호출하면 구성되지 않은 디바이스 오류가 반환됩니다.
packages/story/dungeon_adventure_story/agent/agent.py를 업데이트하세요:
from contextlib import contextmanager
from dungeon_adventure_agent_connection import InventoryMcpServerClientStrands, log_model_errors, log_tool_errorsfrom strands import Agentfrom strands.hooks import HookCallback, HookProvider
AGENT_HOOKS: list[HookProvider | HookCallback] = [log_model_errors, log_tool_errors]
@contextmanagerdef get_agent(): inventory_mcp_server = InventoryMcpServerClientStrands.create() with ( inventory_mcp_server, ): yield Agent( system_prompt="""You are running a text adventure game for a lone adventurer. When a new storybegins, the first user message will tell you the player's name and the genre(one of 'medieval', 'zombie', 'superhero'). Greet the player by name, set thescene in the chosen genre, and populate their inventory with a few startingitems. On subsequent turns, advance the story in response to the player'sactions and keep item state in sync with the narrative.Use the tools to manage the player's inventory as items are obtained or lost.Item names in the inventory must be Title Case — match them exactly.Only use list-inventory-items if you are unsure of the exact item name before modifying it.For an uncertain action, explain the challenge and call roll-dice with 20 sides.For an explicit dice request, use the requested supported die (4, 6, 8, 10, 12 or 20 sides).Call roll-dice at most once per response turn. Use only its returned value andstate the die, result and consequence in your reply. Never invent a roll.If roll-dice fails, tell the player that the dice device is unavailable andask them to retry. Do not decide the challenge or change inventory for it.Call tools sequentially and await each result. After a successful roll you maycall an inventory tool if the outcome awards or consumes an item.Ensure you specify a suitable emoji when adding items if available.Items should be a key part of the narrative.Keep responses under 100 words.""", tools=[*inventory_mcp_server.list_tools_sync()], hooks=AGENT_HOOKS, )from contextlib import contextmanager
from dungeon_adventure_agent_connection import InventoryMcpServerClientStrands, log_model_errors, log_tool_errorsfrom strands import Agentfrom strands.hooks import HookCallback, HookProvider
AGENT_HOOKS: list[HookProvider | HookCallback] = [log_model_errors, log_tool_errors]
@contextmanagerdef get_agent(): inventory_mcp_server = InventoryMcpServerClientStrands.create() with ( inventory_mcp_server, ): yield Agent( system_prompt="""You are running a text adventure game for a lone adventurer. When a new storybegins, the first user message will tell you the player's name and the genre(one of 'medieval', 'zombie', 'superhero'). Greet the player by name, set thescene in the chosen genre, and populate their inventory with a few startingitems. On subsequent turns, advance the story in response to the player'sactions and keep item state in sync with the narrative.Use the tools to manage the player's inventory as items are obtained or lost.Item names in the inventory must be Title Case — match them exactly.Only use list-inventory-items if you are unsure of the exact item name before modifying it.IMPORTANT: Only call ONE tool per response turn. Never batch multiple tool calls in a single turn.For an uncertain action, explain the challenge and call roll-dice with 20 sides.For an explicit dice request, use the requested supported die (4, 6, 8, 10, 12 or 20 sides).Call roll-dice at most once per response turn. Use only its returned value andstate the die, result and consequence in your reply. Never invent a roll.If roll-dice fails, tell the player that the dice device is unavailable andask them to retry. Do not decide the challenge or change inventory for it.Call tools sequentially and await each result. After a successful roll you maycall an inventory tool if the outcome awards or consumes an item.Ensure you specify a suitable emoji when adding items if available.Items should be a key part of the narrative.Keep responses under 100 words.""", tools=[*inventory_mcp_server.list_tools_sync()], hooks=AGENT_HOOKS, )교체는 순차 호출을 허용하므로 성공적인 굴림 다음에 인벤토리 업데이트가 올 수 있습니다. 여전히 턴당 하나의 굴림만 허용하고 주사위 도구가 실패할 때 챌린지를 명시적으로 중지합니다.
4. 디바이스 리소스를 기존 애플리케이션에 구성
섹션 제목: “4. 디바이스 리소스를 기존 애플리케이션에 구성”packages/infra/src/dice-resources.ts를 생성하세요:
import { Dice, GreengrassArtifactBucket, GreengrassDeployment,} from '@dungeon-adventure/common-constructs';import { ArnFormat, CfnOutput, CfnParameter, Stack } from 'aws-cdk-lib';import { Grant, type IGrantable, Role } from 'aws-cdk-lib/aws-iam';import { Construct } from 'constructs';
export class DiceResources extends Construct { readonly environmentVariables: Record<string, string>; readonly deployment: GreengrassDeployment; private readonly shadowArn: string;
constructor(scope: Construct, id: string) { super(scope, id); const stack = Stack.of(this); const thing = new CfnParameter(stack, 'DiceThingName', { type: 'String', allowedPattern: '[a-zA-Z0-9:_-]+', }); const endpoint = new CfnParameter(stack, 'DiceEndpoint', { type: 'String' }); const tokenExchangeRole = new CfnParameter(stack, 'TokenExchangeRoleArn', { type: 'String' }); const group = new CfnParameter(stack, 'ThingGroupArn', { type: 'String' });
this.environmentVariables = { DICE_THING_NAME: thing.valueAsString, DICE_IOT_ENDPOINT: endpoint.valueAsString, DICE_AWS_REGION: stack.region, }; this.shadowArn = stack.formatArn({ service: 'iot', resource: 'thing', resourceName: `${thing.valueAsString}/dungeon-dice`, arnFormat: ArnFormat.SLASH_RESOURCE_NAME, }); const artifacts = new GreengrassArtifactBucket(this, 'Artifacts'); artifacts.grantReadTo( Role.fromRoleArn(this, 'TokenExchangeRole', tokenExchangeRole.valueAsString), 'com.example.DungeonDice/*', ); const component = new Dice(this, 'Component', { bucket: artifacts }); this.deployment = new GreengrassDeployment(this, 'Fleet', { targetArn: group.valueAsString }); this.deployment.addComponent(component); new CfnOutput(stack, 'DiceArtifactBucket', { value: artifacts.bucket.bucketName }); new CfnOutput(stack, 'DiceComponentArn', { value: component.cfnComponentVersion.attrArn }); new CfnOutput(stack, 'DiceDeploymentId', { value: this.deployment.deployment.attrDeploymentId }); }
grantShadowAccess(grantee: IGrantable): Grant { return Grant.addToPrincipal({ grantee, actions: ['iot:GetThingShadow', 'iot:UpdateThingShadow'], resourceArns: [this.shadowArn], }); }}packages/infra/src/stacks/application-stack.ts를 업데이트하여 디바이스
구성을 MCP 서버에 전달하고 런타임에 섀도우에 대한 액세스 권한을 부여하세요:
import { DungeonDb, GameApi, GameUI, InventoryMcpServer, StoryAgent, UserIdentity, suppressRules,} from '@dungeon-adventure/common-constructs';import { Stack, StackProps, CfnOutput, RemovalPolicy } from 'aws-cdk-lib';import { TableEncryption } from 'aws-cdk-lib/aws-dynamodb';import { Construct } from 'constructs';import { DiceResources } from '../dice-resources.js';
export class ApplicationStack extends Stack { constructor(scope: Construct, id: string, props?: StackProps) { super(scope, id, props);
const userIdentity = new UserIdentity(this, 'UserIdentity');
// Sandbox-friendly: allow the table to be deleted with the stack. const dungeonDb = new DungeonDb(this, 'DungeonDb', { deletionProtection: false, removalPolicy: RemovalPolicy.DESTROY, encryption: TableEncryption.DEFAULT, }); suppressRules( dungeonDb.table, ['CKV_AWS_119'], 'Sandbox stack uses the AWS owned key so it can be torn down and recreated freely', );
const gameApi = new GameApi(this, 'GameApi', { integrations: GameApi.defaultIntegrations(this).build(), });
dungeonDb.grantReadData(gameApi.integrations['games.query'].handler); dungeonDb.grantReadData(gameApi.integrations['inventory.query'].handler); dungeonDb.grantReadWriteData(gameApi.integrations['games.save'].handler);
const dice = new DiceResources(this, 'DiceResources'); const mcpServer = new InventoryMcpServer(this, 'InventoryMcpServer', { environmentVariables: dice.environmentVariables, }); dice.grantShadowAccess(mcpServer.agentCoreRuntime); dungeonDb.grantReadWriteData(mcpServer.agentCoreRuntime);
// Use Cognito for user authentication with the agent const storyAgent = new StoryAgent(this, 'StoryAgent', { identity: userIdentity, }); // The agent's own session bucket already persists conversation history via // S3SessionManager; grant the Game API read access so it can replay it. storyAgent.sessionBucket.grantRead( gameApi.integrations['actions.query'].handler, );
new CfnOutput(this, 'StoryAgentArn', { value: storyAgent.agentCoreRuntime.agentRuntimeArn, }); new CfnOutput(this, 'InventoryMcpArn', { value: mcpServer.agentCoreRuntime.agentRuntimeArn, });
// Grant the agent permissions to invoke our mcp server mcpServer.grantInvokeAccess(storyAgent);
// Grant the authenticated role access to invoke the api gameApi.grantInvokeAccess(userIdentity.identityPool.authenticatedRole);
new GameUI(this, 'GameUI'); }}import { DungeonDb, GameApi, GameUI, InventoryMcpServer, StoryAgent, UserIdentity, suppressRules,} from '@dungeon-adventure/common-constructs';import { Stack, StackProps, CfnOutput, RemovalPolicy } from 'aws-cdk-lib';import { TableEncryption } from 'aws-cdk-lib/aws-dynamodb';import { Construct } from 'constructs';import { DiceResources } from '../dice-resources.js';
export class ApplicationStack extends Stack { constructor(scope: Construct, id: string, props?: StackProps) { super(scope, id, props);
const userIdentity = new UserIdentity(this, 'UserIdentity');
// Sandbox-friendly: allow the table to be deleted with the stack. const dungeonDb = new DungeonDb(this, 'DungeonDb', { deletionProtection: false, removalPolicy: RemovalPolicy.DESTROY, encryption: TableEncryption.DEFAULT, }); suppressRules( dungeonDb.table, ['CKV_AWS_119'], 'Sandbox stack uses the AWS owned key so it can be torn down and recreated freely', );
const gameApi = new GameApi(this, 'GameApi', { integrations: GameApi.defaultIntegrations(this).build(), });
dungeonDb.grantReadData(gameApi.integrations['games.query'].handler); dungeonDb.grantReadData(gameApi.integrations['inventory.query'].handler); dungeonDb.grantReadWriteData(gameApi.integrations['games.save'].handler);
const mcpServer = new InventoryMcpServer(this, 'InventoryMcpServer'); const dice = new DiceResources(this, 'DiceResources'); const mcpServer = new InventoryMcpServer(this, 'InventoryMcpServer', { environmentVariables: dice.environmentVariables, }); dice.grantShadowAccess(mcpServer.agentCoreRuntime); dungeonDb.grantReadWriteData(mcpServer.agentCoreRuntime);
// Use Cognito for user authentication with the agent const storyAgent = new StoryAgent(this, 'StoryAgent', { identity: userIdentity, }); // The agent's own session bucket already persists conversation history via // S3SessionManager; grant the Game API read access so it can replay it. storyAgent.sessionBucket.grantRead( gameApi.integrations['actions.query'].handler, );
new CfnOutput(this, 'StoryAgentArn', { value: storyAgent.agentCoreRuntime.agentRuntimeArn, }); new CfnOutput(this, 'InventoryMcpArn', { value: mcpServer.agentCoreRuntime.agentRuntimeArn, });
// Grant the agent permissions to invoke our mcp server mcpServer.grantInvokeAccess(storyAgent);
// Grant the authenticated role access to invoke the api gameApi.grantInvokeAccess(userIdentity.identityPool.authenticatedRole);
new GameUI(this, 'GameUI'); }}기존 애플리케이션 스택의 나머지 부분을 유지하세요. DiceResources는
디바이스 매개변수, 아티팩트 권한 부여, 컴포넌트 및 그
배포를 소유합니다.
세 가지 권한 경계가 있습니다:
- 코어의 기존 IoT 인증서 정책은
$aws/things/<thing-name>/shadow/*에 대한 게시, 구독 및 수신을 허용하며, 여기에는 이미 명명된dungeon-dice섀도우가 포함됩니다. 추가 인증서 정책이 필요하지 않습니다. - 주사위 레시피는 IPC를 통해 해당 주제에 대한 컴포넌트 액세스 권한을 부여합니다.
- Inventory MCP 런타임은 이 사물의 명명된
dungeon-dice섀도우에만GetThingShadow및UpdateThingShadow를 받습니다.
아티팩트 권한 부여는 코어의 토큰 교환 역할이 com.example.DungeonDice/*만
가져올 수 있도록 합니다. 배포는 컴포넌트 게시에 따라 달라집니다.
빌드한 다음 네 가지 매개변수 값으로 모두 배포하세요:
pnpm nx syncyarn nx syncnpx nx syncbunx nx syncpnpm installyarnnpm installbun installpnpm lintyarn lintnpm run lintbun lintpnpm nx run-many --target build --allyarn nx run-many --target build --allnpx nx run-many --target build --allbunx nx run-many --target build --allAWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" pnpm nx run @dungeon-adventure/infra:deploy -- "dungeon-adventure-infra-sandbox/**" --parameters dungeon-adventure-infra-sandbox-Application:DiceThingName="$TUTORIAL_THING_NAME" --parameters dungeon-adventure-infra-sandbox-Application:DiceEndpoint="$DICE_IOT_ENDPOINT" --parameters dungeon-adventure-infra-sandbox-Application:TokenExchangeRoleArn="$TUTORIAL_TOKEN_EXCHANGE_ROLE_ARN" --parameters dungeon-adventure-infra-sandbox-Application:ThingGroupArn="$TUTORIAL_THING_GROUP_ARN"AWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" yarn nx run @dungeon-adventure/infra:deploy -- "dungeon-adventure-infra-sandbox/**" --parameters dungeon-adventure-infra-sandbox-Application:DiceThingName="$TUTORIAL_THING_NAME" --parameters dungeon-adventure-infra-sandbox-Application:DiceEndpoint="$DICE_IOT_ENDPOINT" --parameters dungeon-adventure-infra-sandbox-Application:TokenExchangeRoleArn="$TUTORIAL_TOKEN_EXCHANGE_ROLE_ARN" --parameters dungeon-adventure-infra-sandbox-Application:ThingGroupArn="$TUTORIAL_THING_GROUP_ARN"AWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" npx nx run @dungeon-adventure/infra:deploy -- "dungeon-adventure-infra-sandbox/**" --parameters dungeon-adventure-infra-sandbox-Application:DiceThingName="$TUTORIAL_THING_NAME" --parameters dungeon-adventure-infra-sandbox-Application:DiceEndpoint="$DICE_IOT_ENDPOINT" --parameters dungeon-adventure-infra-sandbox-Application:TokenExchangeRoleArn="$TUTORIAL_TOKEN_EXCHANGE_ROLE_ARN" --parameters dungeon-adventure-infra-sandbox-Application:ThingGroupArn="$TUTORIAL_THING_GROUP_ARN"AWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" bunx nx run @dungeon-adventure/infra:deploy -- "dungeon-adventure-infra-sandbox/**" --parameters dungeon-adventure-infra-sandbox-Application:DiceThingName="$TUTORIAL_THING_NAME" --parameters dungeon-adventure-infra-sandbox-Application:DiceEndpoint="$DICE_IOT_ENDPOINT" --parameters dungeon-adventure-infra-sandbox-Application:TokenExchangeRoleArn="$TUTORIAL_TOKEN_EXCHANGE_ROLE_ARN" --parameters dungeon-adventure-infra-sandbox-Application:ThingGroupArn="$TUTORIAL_THING_GROUP_ARN"WAF 스택이 매개변수를 정의하지 않으므로 애플리케이션 스택에 대한 매개변수를 한정하세요.
이 워크스루에는 deploy를 사용하세요. 컴포넌트/버전 변경은
CloudFormation 리소스를 교체합니다. 배포 수정은
deploy-sandbox에 필요한 추가 롤백 플래그를 설명합니다.
컴포넌트가 RUNNING이 될 때까지 기다리세요:
aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" \ greengrassv2 list-installed-components --core-device-thing-name "$TUTORIAL_THING_NAME" \ --query "installedComponents[?componentName=='com.example.DungeonDice'].[componentVersion,lifecycleState]" \ --output table5. 에이전트가 굴리도록 하기
섹션 제목: “5. 에이전트가 굴리도록 하기”배포된 게임을 열고 새 대화를 시작하거나 기존 대화를 다시 로드한 다음 물어보세요:
“이 자물쇠를 따려는 시도를 위해 주사위 디바이스에서 d20을 굴려주세요.”
에이전트는 roll-dice를 호출하고 반환된 값과 결과를 설명해야 합니다.
클라우드 섀도우를 읽어 reported.result를 도구 결과 및 에이전트의 응답과 비교하세요:
aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" \ iot-data get-thing-shadow --endpoint-url "https://${DICE_IOT_ENDPOINT}" \ --thing-name "$TUTORIAL_THING_NAME" --shadow-name dungeon-dice \ /tmp/dungeon-dice-shadow.jsoncat /tmp/dungeon-dice-shadow.json성공적인 결과에는 requestId, sides, value 및 rolledAt이 포함됩니다.
/greengrass/v2/logs/com.example.DungeonDice.log의 디바이스 로그는
동일한 요청 ID와 값을 기록합니다. 성공적인 배포만으로는 이 왕복을 증명하지 못합니다.
실패 경로를 실행하려면 Systems Manager 터미널을 통해 이 일회용 코어에서 Greengrass 서비스를 중지하고, 다른 굴림을 요청하고, 제한된 대기 후 도구가 오류를 보고하는지 확인하세요. 에이전트는 챌린지를 결정하는 대신 디바이스를 사용할 수 없다고 알려야 합니다. 계속하기 전에 서비스를 다시 시작하세요. 만료된 대기 중인 요청은 디바이스가 다시 연결될 때 굴려서는 안 됩니다. 새 도구 호출은 새 요청을 생성합니다.
버전 업데이트 실습을 위해 컴포넌트의 로그 메시지를 변경하고 다시 빌드한 다음
동일한 배포 명령을 실행하세요. NEXT_PATCH는 새 버전을 게시합니다.
새로 실행 중인 버전을 확인한 다음 다른 굴림을 요청하세요.
6. 계속 플레이하거나 모두 제거
섹션 제목: “6. 계속 플레이하거나 모두 제거”확장만 제거하려면:
- 애플리케이션 스택에서
DiceArtifactBucket,DiceComponentArn및DiceDeploymentId출력을 기록하세요. packages/infra/src/dice-resources.ts에서this.deployment.addComponent(component)를 제거하세요. 동일한 매개변수로 재배포하세요. 이렇게 하면 빈 배포 수정이 전송됩니다.list-installed-components가 더 이상com.example.DungeonDice를 나열하지 않을 때까지 기다리세요.- 기본 Story Agent 프롬프트를 복원하고,
registerDiceToolimport 및 호출을 제거하고, 모듈 2 애플리케이션 스택을 복원하세요. 던전을 다시 빌드하고 배포하세요. 이렇게 하면 MCP 권한 및 주사위 구성이 제거됩니다. - 보존된 리소스 정리 절차를 사용하여
보존된 Greengrass 배포 레코드, 컴포넌트 버전 및 아티팩트 버킷을 삭제하세요.
com.example.Pulse를com.example.DungeonDice로 대체하고 기록된 주사위 출력을 사용하세요. 업데이트 실습으로 생성된 모든 버전/수정을 포함하세요. - 명명된 섀도우를 삭제한 다음 설정 스크립트의 정리를 실행하고 디바이스 정리 가이드에 설명된 대로 소유자 관리 인스턴스 프로필 및 역할을 제거하세요.
aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" \ iot-data delete-thing-shadow --endpoint-url "https://${DICE_IOT_ENDPOINT}" \ --thing-name "$TUTORIAL_THING_NAME" --shadow-name dungeon-dice \ /tmp/dungeon-dice-shadow-deleted.json이러한 단계 후에도 던전은 배포된 상태로 유지됩니다. 전체 애플리케이션을 제거하려면 보존된 사용자 풀, SMS 역할 및 대화 기록 버킷을 포함하여 리소스 파괴를 계속하세요.
추가 실험
섹션 제목: “추가 실험”- 64비트 OS와 물리적 센서가 있는 Raspberry Pi를 사용하세요.
secrets.randbelow를 교체하는 동안 요청 ID 및 시간 초과 계약을 유지하세요. - ESP32를 사용하여 센서를 읽고 그 결과를 Linux 게이트웨이로 보내세요. 이렇게 하면 펌웨어 및 디바이스 인증이 추가됩니다. 이 Python 컴포넌트의 다른 CPU 대상이 아닙니다.
- 컴포넌트를 로컬 주사위 엔진과 Greengrass pub/sub를 통해 연결된 MQTT 브리지로 분할하세요.