콘텐츠로 이동

게임 API 및 인벤토리 MCP 서버 구현

Game API를 구현하기 전에 다음 5개의 API를 생성해야 합니다:

  1. saveGame - 게임 생성 또는 업데이트
  2. queryGames - 저장된 게임 목록을 페이지네이션으로 반환
  3. saveAction - 특정 게임에 대한 액션 저장
  4. queryActions - 게임 관련 모든 액션의 페이지네이션 목록 반환
  5. queryInventory - 플레이어 인벤토리 아이템 목록을 페이지네이션으로 반환

Zod를 사용하여 API 입력/출력 스키마를 packages/game-api/src/schema 디렉토리에 다음과 같이 정의합니다:

import { z } from 'zod';
export const ActionSchema = z.object({
playerName: z.string(),
timestamp: z.iso.datetime(),
role: z.enum(['assistant', 'user']),
content: z.string(),
});
export type IAction = z.TypeOf<typeof ActionSchema>;

이 프로젝트에서 사용하지 않을 packages/game-api/src/schema/echo.ts 파일은 삭제할 수 있습니다.

애플리케이션의 ER 다이어그램은 다음과 같습니다.

dungeon-adventure-er.png

DynamoDB에 데이터베이스를 구현할 것이며, ElectroDB DynamoDB 클라이언트 라이브러리를 사용하여 작업을 단순화합니다. electrodb와 DynamoDB 클라이언트를 설치하려면 다음 명령어를 실행합니다:

Terminal window
pnpm add -w electrodb@3.5.0 @aws-sdk/client-dynamodb@3.914.0

ER 다이어그램에서 ElectroDB 엔티티를 정의하기 위해 packages/game-api/src/entities 폴더 내에 다음 파일들을 생성합니다:

import { Entity } from 'electrodb';
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
export const createActionEntity = (client?: DynamoDBClient) =>
new Entity(
{
model: {
entity: 'Action',
version: '1',
service: 'game',
},
attributes: {
playerName: { type: 'string', required: true, readOnly: true },
timestamp: {
type: 'string',
required: true,
readOnly: true,
set: () => new Date().toISOString(),
default: () => new Date().toISOString(),
},
role: { type: 'string', required: true, readOnly: true },
content: { type: 'string', required: true, readOnly: true },
},
indexes: {
primary: {
pk: { field: 'pk', composite: ['playerName'] },
sk: { field: 'sk', composite: ['timestamp'] },
},
},
},
{ client, table: process.env.TABLE_NAME },
);

ElectroDB를 사용하면 타입 정의뿐만 아니라 타임스탬프와 같은 특정 값에 대한 기본값을 제공할 수 있습니다. 또한 ElectroDB는 DynamoDB 사용 시 권장되는 단일 테이블 디자인을 따릅니다.

MCP 서버가 인벤토리와 상호작용할 수 있도록 packages/game-api/src/index.ts에서 인벤토리 엔티티를 내보내야 합니다:

export type { AppRouter } from './router.js';
export { appRouter } from './router.js';
export type { Context } from './init.js';
export * from './client/index.js';
export * from './schema/index.js';
export * from './entities/inventory.js';

tRPC 컨텍스트에 DynamoDB 클라이언트 추가

섹션 제목: “tRPC 컨텍스트에 DynamoDB 클라이언트 추가”

모든 프로시저에서 DynamoDB 클라이언트에 접근할 수 있도록 컨텍스트를 통해 단일 인스턴스를 전달해야 합니다. 이를 위해 packages/game-api/src 내에서 다음 변경사항을 적용합니다:

import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import { initTRPC } from '@trpc/server';
export interface IDynamoDBContext {
dynamoDb?: DynamoDBClient;
}
export const createDynamoDBPlugin = () => {
const t = initTRPC.context<IDynamoDBContext>().create();
return t.procedure.use(async (opts) => {
const dynamoDb = new DynamoDBClient();
const response = await opts.next({
ctx: {
...opts.ctx,
dynamoDb,
},
});
return response;
});
};

이 플러그인은 DynamoDBClient를 생성하고 컨텍스트에 주입합니다.

API 메서드를 구현하기 위해 packages/game-api/src/procedures 내에서 다음 변경사항을 적용합니다:

import { createActionEntity } from '../entities/action.js';
import {
ActionSchema,
IAction,
QueryInputSchema,
createPaginatedQueryOutput,
} from '../schema/index.js';
import { publicProcedure } from '../init.js';
import { z } from 'zod';
export const queryActions = publicProcedure
.input(QueryInputSchema.extend({ playerName: z.string() }))
.output(createPaginatedQueryOutput(ActionSchema))
.query(async ({ input, ctx }) => {
const actionEntity = createActionEntity(ctx.dynamoDb);
const result = await actionEntity.query
.primary({ playerName: input.playerName })
.go({ cursor: input.cursor, count: input.limit });
return {
items: result.data as IAction[],
cursor: result.cursor,
};
});
import { ActionSchema, IAction } from '../schema/index.js';
import { publicProcedure } from '../init.js';
import { createActionEntity } from '../entities/action.js';
import { createGameEntity } from '../entities/game.js';
export const saveAction = publicProcedure
.input(ActionSchema.omit({ timestamp: true }))
.output(ActionSchema)
.mutation(async ({ input, ctx }) => {
const actionEntity = createActionEntity(ctx.dynamoDb);
const gameEntity = createGameEntity(ctx.dynamoDb);
const action = await actionEntity.put(input).go();
await gameEntity
.update({ playerName: input.playerName })
.set({ lastUpdated: action.data.timestamp })
.go();
return action.data as IAction;
});

이 프로젝트에서 사용하지 않을 echo.ts 파일(packages/game-api/src/procedures 내)은 삭제할 수 있습니다.

프로시저를 정의한 후 API에 연결하기 위해 다음 파일을 업데이트합니다:

import {
awsLambdaRequestHandler,
CreateAWSLambdaContextOptions,
} from '@trpc/server/adapters/aws-lambda';
import { t } from './init.js';
import { APIGatewayProxyEvent } from 'aws-lambda';
import { queryActions } from './procedures/query-actions.js';
import { saveAction } from './procedures/save-action.js';
import { queryGames } from './procedures/query-games.js';
import { saveGame } from './procedures/save-game.js';
import { queryInventory } from './procedures/query-inventory.js';
export const router = t.router;
export const appRouter = router({
actions: router({
query: queryActions,
save: saveAction,
}),
games: router({
query: queryGames,
save: saveGame,
}),
inventory: router({
query: queryInventory,
}),
});
export const handler = awsLambdaRequestHandler({
router: appRouter,
createContext: (
ctx: CreateAWSLambdaContextOptions<APIGatewayProxyEvent>,
) => ctx,
responseMeta: () => ({
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': '*',
},
}),
});
export type AppRouter = typeof appRouter;

에이전트가 플레이어 인벤토리 아이템을 관리할 수 있는 MCP 서버를 생성합니다.

에이전트를 위해 다음 도구들을 정의합니다:

  • list-inventory-items: 플레이어의 현재 인벤토리 아이템 조회
  • add-to-inventory: 인벤토리에 아이템 추가
  • remove-from-inventory: 인벤토리에서 아이템 제거

시간 절약을 위해 모든 도구를 인라인으로 정의합니다:

import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import z from 'zod-v3';
import { createInventoryEntity } from ':dungeon-adventure/game-api';
/**
* Create the MCP Server
*/
export const createServer = () => {
const server = new McpServer({
name: 'inventory-mcp-server',
version: '1.0.0',
});
const dynamoDb = new DynamoDBClient();
const inventory = createInventoryEntity(dynamoDb);
server.tool(
'list-inventory-items',
"List items in the player's inventory. Leave cursor blank unless you are requesting subsequent pages",
{
playerName: z.string(),
cursor: z.string().optional(),
},
async ({ playerName }) => {
const results = await inventory.query
.primary({
playerName,
})
.go();
return {
content: [{ type: 'text', text: JSON.stringify(results) }],
};
},
);
server.tool(
'add-to-inventory',
"Add an item to the player's inventory. Quantity defaults to 1 if omitted.",
{
playerName: z.string(),
itemName: z.string(),
emoji: z.string(),
quantity: z.number().optional().default(1),
},
async ({ playerName, itemName, emoji, quantity = 1 }) => {
await inventory
.put({
playerName,
itemName,
quantity,
emoji,
})
.go();
return {
content: [
{
type: 'text',
text: `Added ${itemName} (x${quantity}) to inventory`,
},
],
};
},
);
server.tool(
'remove-from-inventory',
"Remove an item from the player's inventory. If quantity is omitted, all items are removed.",
{
playerName: z.string(),
itemName: z.string(),
quantity: z.number().optional(),
},
async ({ playerName, itemName, quantity }) => {
// If quantity is omitted, remove the entire item
if (quantity === undefined) {
try {
await inventory.delete({ playerName, itemName }).go();
return {
content: [
{ type: 'text', text: `${itemName} removed from inventory.` },
],
} as const;
} catch {
return {
content: [
{ type: 'text', text: `${itemName} not found in inventory` },
],
} as const;
}
}
// If quantity is specified, fetch current quantity and update
const item = await inventory.get({ playerName, itemName }).go();
if (!item.data) {
return {
content: [
{ type: 'text', text: `${itemName} not found in inventory` },
],
} as const;
}
const newQuantity = item.data.quantity - quantity;
if (newQuantity <= 0) {
await inventory.delete({ playerName, itemName }).go();
return {
content: [
{ type: 'text', text: `${itemName} removed from inventory.` },
],
} as const;
}
await inventory
.put({
playerName,
itemName,
quantity: newQuantity,
emoji: item.data.emoji,
})
.go();
return {
content: [
{
type: 'text',
text: `Removed ${itemName} (x${quantity}) from inventory. ${newQuantity} remaining.`,
},
],
};
},
);
return server;
};

도구 수가 증가하면 별도 파일로 리팩토링할 수 있습니다.

사용되지 않을 packages/inventory/src/mcp-server 내의 toolsresources 디렉토리를 삭제합니다.

마지막 단계로 DynamoDB 테이블을 생성하고 Game API에서 작업 권한을 부여하기 위해 인프라를 업데이트합니다. 이를 위해 packages/infra/src를 다음과 같이 수정합니다:

import { CfnOutput } from 'aws-cdk-lib';
import {
AttributeType,
BillingMode,
ProjectionType,
Table,
TableProps,
} from 'aws-cdk-lib/aws-dynamodb';
import { Construct } from 'constructs';
import { suppressRules } from ':dungeon-adventure/common-constructs';
export type ElectrodbDynamoTableProps = Omit<
TableProps,
'partitionKey' | 'sortKey' | 'billingMode'
>;
export class ElectrodbDynamoTable extends Table {
constructor(scope: Construct, id: string, props?: ElectrodbDynamoTableProps) {
super(scope, id, {
partitionKey: {
name: 'pk',
type: AttributeType.STRING,
},
sortKey: {
name: 'sk',
type: AttributeType.STRING,
},
billingMode: BillingMode.PAY_PER_REQUEST,
...props,
});
this.addGlobalSecondaryIndex({
indexName: 'gsi1pk-gsi1sk-index',
partitionKey: {
name: 'gsi1pk',
type: AttributeType.STRING,
},
sortKey: {
name: 'gsi1sk',
type: AttributeType.STRING,
},
projectionType: ProjectionType.ALL,
});
// Suppress checkov rules that expect a KMS customer managed key and backup to be enabled
suppressRules(this, ['CKV_AWS_119', 'CKV_AWS_28'], 'No need for custom encryption or backup');
new CfnOutput(this, 'TableName', { value: this.tableName });
}
}

코드베이스를 빌드하려면:

Terminal window
pnpm nx run-many --target build --all

애플리케이션을 배포하려면 다음 명령어를 실행합니다:

Terminal window
pnpm nx deploy infra dungeon-adventure-infra-sandbox/*

첫 배포는 약 8분 정도 소요됩니다. 이후 배포는 약 2분 정도 걸립니다.

배포가 완료되면 다음과 유사한 출력을 확인할 수 있습니다 (일부 값은 편집됨):

Terminal window
dungeon-adventure-sandbox-Application
dungeon-adventure-sandbox-Application: deploying... [2/2]
dungeon-adventure-sandbox-Application
Deployment time: 354s
Outputs:
dungeon-adventure-sandbox-Application.ElectroDbTableTableNameXXX = dungeon-adventure-sandbox-Application-ElectroDbTableXXX-YYY
dungeon-adventure-sandbox-Application.GameApiEndpointXXX = https://xxx.execute-api.region.amazonaws.com/prod/
dungeon-adventure-sandbox-Application.GameUIDistributionDomainNameXXX = xxx.cloudfront.net
dungeon-adventure-sandbox-Application.StoryApiEndpointXXX = https://xxx.execute-api.region.amazonaws.com/prod/
dungeon-adventure-sandbox-Application.UserIdentityUserIdentityIdentityPoolIdXXX = region:xxx
dungeon-adventure-sandbox-Application.UserIdentityUserIdentityUserPoolIdXXX = region_xxx

다음 방법으로 API를 테스트할 수 있습니다:

  • tRPC 백엔드 로컬 인스턴스를 시작하고 curl로 API 호출
  • 배포된 API를 Sigv4 활성화된 curl로 호출

로컬 game-api 서버를 시작하려면 다음 명령어를 실행합니다:

Terminal window
TABLE_NAME=dungeon-adventure-infra-sandbox-Application-ElectroDbTableXXX-YYY pnpm nx run @dungeon-adventure/game-api:serve

서버가 실행되면 다음 명령어로 호출할 수 있습니다:

Terminal window
curl -X GET 'http://localhost:2022/games.query?input=%7B%7D'

명령어가 성공적으로 실행되면 다음과 같은 응답을 확인할 수 있습니다:

{"result":{"data":{"items":[],"cursor":null}}}

축하합니다! tRPC를 사용하여 첫 번째 API를 구축하고 배포했습니다! 🎉🎉🎉