Skip to content

オプション: Greengrassでサイコロを振る

モジュール4でデプロイしたダンジョンを維持してください。 破棄する前に、Story Agentにサイコロデバイスを与えます:

“I try to pick the lock. Roll a d20 to see whether I succeed.”

エージェントはroll-diceを呼び出します。Greengrassコア上のPythonコンポーネントがロールを生成し、MCPツールはそのデバイスの結果をエージェントに返します。返信は「d20: 17」と言い、結果を説明できます。

このオプションルートは、ソフトウェアサイコロシミュレーターを備えたEC2コアを使用します。後で、その乱数関数を物理的なサイコロトレイからの入力に置き換えることができます。 スタンドアロンのGreengrassチュートリアルは、空のワークスペースからコンポーネント生成を学ぶための別の方法として残ります。

Diagram

クラウドシャドウは、1つの保留中のリクエストと最新の結果を保持します。ツールは最大12秒待機します。フォールバックロールは生成しません。バージョンチェックにより、同時呼び出し元がアクティブなリクエストを置き換えることを防ぎます。デバイスは公開前に最後の結果を保存するため、MQTTの再配信とコンポーネントの再起動は同じリクエストを再ロールしません。

このサンドボックスは、プレイヤー間で1つのサイコロデバイスを共有します。ビジーなデバイスはエラーを返します。フリート全体のキューを追加したり、個人用デバイスをCognitoユーザーに関連付けたりしません。これらは、マルチプレイヤー製品のための別の拡張です。

1. ダンジョンを破棄せずにコアをプロビジョニングする

Section titled “1. ダンジョンを破棄せずにコアをプロビジョニングする”

デプロイされたダンジョンと同じAWSアカウントとリージョンを使用します。プロファイルを明示的に設定し、デバイスリソースに新しいプレフィックスを使用します:

Terminal window
export TUTORIAL_AWS_PROFILE=<your-dungeon-profile>
export TUTORIAL_AWS_REGION=<your-dungeon-region>
export TUTORIAL_PREFIX=gg-dungeon-dice

ダンジョンワークスペースからコアデバイスのプロビジョニングに従ってください。一時的なインストーラーポリシーの削除も含みます。そのページはインスタンスを作成し、.greengrass-tutorial.envを書き込みます。 別のNxワークスペースを作成したり、スタンドアロンのハートビートモジュールを実行したりしないでください。 セットアップスクリプトの既存のデフォルトは変更されません。

Terminal window
source .greengrass-tutorial.env
export DICE_IOT_ENDPOINT=$(aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" \
iot describe-endpoint --endpoint-type iot:Data-ATS --query endpointAddress --output text)

ツールを有効にする前に、新しいデバイスの名前付きシャドウを一度初期化します。アクティブなサイコロリクエストを持つデバイスに対してこのリセットを実行しないでください:

Terminal window
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.json

EC2ウォークスルーはx86_64 Linuxを使用します。64ビットLinuxを実行するRaspberry Piは代わりにlinux-arm64を使用します。生成されたレシピとネイティブ依存関係の両方がそのアーキテクチャをターゲットにする必要があります。ハードウェアサポートを参照してください。 ESP32はゲートウェイにセンサー入力を供給できますが、このPythonコンポーネントを実行することはできません。

2. サイコロコンポーネントを生成する

Section titled “2. サイコロコンポーネントを生成する”

デバイスアーティファクトがStory Agentのクラウド依存関係を持たないように、別のPythonホストを作成します:

このジェネレーターを実行@aws/nx-plugin:py#project

pnpm nx g @aws/nx-plugin:py#project --name=edge --no-interactive
このステップのオプション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
このステップのオプション9

必須

必須

packages/edge/greengrass/dice/main.pyを置き換えます:

import argparse
import json
import logging
import os
import queue
import secrets
import time
import uuid
from pathlib import Path
from 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.DungeonDice
ComponentVersion: NEXT_PATCH
ComponentDescription: Dice rolls requested by the Dungeon Adventure Story Agent.
ComponentPublisher: dungeon-adventure
ComponentConfiguration:
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/rejected
Manifests:
- 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.util
import os
import tempfile
import unittest
import uuid
from importlib.machinery import SourceFileLoader
from pathlib import Path
from 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 None
dice_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. エージェントのサイコロツールを追加する

Section titled “3. エージェントのサイコロツールを追加する”

Inventory MCPプロジェクトにIoTデータプレーンクライアントを追加します:

Terminal window
pnpm add @aws-sdk/client-iot-data-plane@3.1169.0 --filter inventory

packages/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;
};

3つのインベントリツールすべてを保持します。生成されたStory Agent接続は、すでにこのサーバーからツールを検出しているため、roll-diceも検出します。 ツールはサイコロのサイズのみを受け入れます。デバイスIDとエンドポイントはサーバーの設定から取得されます。モデルは別のデバイスやMQTTトピックを選択できません。 ローカル開発中、インベントリツールはDICE_*環境変数なしでも使用可能なままです。roll-diceを呼び出すと、DICE_THING_NAME、DICE_IOT_ENDPOINT、DICE_AWS_REGIONが設定されるまで、未設定デバイスエラーが返されます。

packages/story/dungeon_adventure_story/agent/agent.pyを更新します:

from contextlib import contextmanager
from dungeon_adventure_agent_connection import InventoryMcpServerClientStrands, log_model_errors, log_tool_errors
from strands import Agent
from strands.hooks import HookCallback, HookProvider
AGENT_HOOKS: list[HookProvider | HookCallback] = [log_model_errors, log_tool_errors]
@contextmanager
def 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 story
begins, 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 the
scene in the chosen genre, and populate their inventory with a few starting
items. On subsequent turns, advance the story in response to the player's
actions 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 and
state 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 and
ask 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 may
call 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,
)

この置き換えにより、成功したロールの後にインベントリの更新が続くように、順次呼び出しが許可されます。ターンごとに1つのロールのみを許可し、サイコロツールが失敗したときにチャレンジを明示的に停止します。

4. デバイスリソースを既存のアプリケーションに構成する

Section titled “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');
}
}

既存のアプリケーションスタックの残りを保持します。DiceResourcesは、デバイスパラメータ、アーティファクト許可、コンポーネントとそのデプロイメントを所有します。

3つのパーミッション境界があります:

  • コアの既存のIoT証明書ポリシーは、$aws/things/<thing-name>/shadow/*での公開、サブスクライブ、受信を許可しており、これには名前付きdungeon-diceシャドウがすでに含まれています。追加の証明書ポリシーは必要ありません。
  • サイコロレシピは、IPCを通じてこれらのトピックへのアクセスをコンポーネントに許可します。
  • Inventory MCPランタイムは、このモノの名前付きdungeon-diceシャドウのみに対してGetThingShadowとUpdateThingShadowを取得します。

アーティファクト許可により、コアのトークン交換ロールはcom.example.DungeonDice/*のみをフェッチできます。デプロイメントはコンポーネントの公開に依存します。

ビルドしてから、4つのパラメータ値すべてを使用してデプロイします:

Terminal window
pnpm nx sync
Terminal window
pnpm install
Terminal window
pnpm lint
Terminal window
pnpm nx run-many --target build --all
Terminal window
AWS_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"

WAFスタックがパラメータを定義していないため、アプリケーションスタックのパラメータを修飾します。

このウォークスルーにはdeployを使用します。コンポーネント/バージョンの変更はCloudFormationリソースを置き換えます。デプロイメントリビジョンは、deploy-sandboxで必要な追加のロールバックフラグを説明しています。

コンポーネントがRUNNINGになるまで待ちます:

Terminal window
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 table

5. エージェントにロールさせる

Section titled “5. エージェントにロールさせる”

デプロイされたゲームを開き、新しい会話を開始するか既存の会話をリロードして、次のように尋ねます:

“Roll a d20 on the dice device for my attempt to pick this lock.”

エージェントはroll-diceを呼び出し、返された値と結果を説明するはずです。クラウドシャドウを読み取って、そのreported.resultをツールの結果とエージェントの返信と比較します:

Terminal window
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.json
cat /tmp/dungeon-dice-shadow.json

成功した結果には、requestId、sides、value、rolledAtが含まれます。 /greengrass/v2/logs/com.example.DungeonDice.logのデバイスログは、同じリクエストIDと値を記録します。デプロイメントの成功だけでは、このラウンドトリップを証明しません。

失敗パスを実行するには、この使い捨てコアのGreengrassサービスをSystems Managerターミナルから停止し、別のロールをリクエストし、ツールが制限された待機後にエラーを報告することを確認します。エージェントは、チャレンジを決定する代わりに、デバイスが利用できないことを伝えるはずです。続行する前にサービスを再起動します。期限切れの保留中のリクエストは、デバイスが再接続したときにロールしてはいけません。新しいツール呼び出しは新しいリクエストを作成します。

バージョン更新の演習として、コンポーネントのログメッセージを変更し、リビルドして同じdeployコマンドを実行します。NEXT_PATCHは新しいバージョンを公開します。新しい実行中のバージョンを確認してから、別のロールをリクエストします。

6. プレイを続けるか、すべてを削除する

Section titled “6. プレイを続けるか、すべてを削除する”

拡張機能のみを削除するには:

  1. アプリケーションスタックからDiceArtifactBucket、DiceComponentArn、DiceDeploymentIdの出力を記録します。
  2. packages/infra/src/dice-resources.tsからthis.deployment.addComponent(component)を削除します。同じパラメータで再デプロイします。 これにより空のデプロイメントリビジョンが送信されます。list-installed-componentsがcom.example.DungeonDiceをリストしなくなるまで待ちます。
  3. ベースのStory Agentプロンプトを復元し、registerDiceToolのインポートと呼び出しを削除し、モジュール2のアプリケーションスタックを復元します。 ダンジョンをリビルドしてデプロイします。これにより、MCPパーミッションとそのサイコロ設定が削除されます。
  4. 保持されたリソースのクリーンアップ手順を使用して、保持されたGreengrassデプロイメントレコード、コンポーネントバージョン、およびアーティファクトバケットを削除します。 com.example.Pulseをcom.example.DungeonDiceに置き換え、記録されたサイコロの出力を使用します。更新演習で作成されたすべてのバージョン/リビジョンを含めます。
  5. 名前付きシャドウを削除してから、デバイスクリーンアップガイドに記載されているように、セットアップスクリプトのクリーンアップを実行し、所有者管理のインスタンスプロファイルとロールを削除します。
Terminal window
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ブリッジに分割します。