Communitygithub.com

tinystruct-patterns

tinystruct Javaフレームワークを使用した開発のためのエキスパートガイダンス。Applicationクラスの作成、@Actionアノテーションによるルーティング、単体テスト、HTTP/CLIデュアルモード対応、イベントシステム、データベース永続化、SSE、ファイルアップロード、HTTP通信を含むプロジェクトで使用します。

tinystruct-patterns とは?

このスキルは、軽量で高性能なJavaフレームワーク「tinystruct」を用いたモジュール開発のための包括的なガイダンスを提供します。tinystructの核となる設計思想は「CLIとHTTPを同等の市民として扱う」ことであり、`@Action`アノテーションを付与したメソッドは、ターミナルとWebブラウザの両方から修正なく実行可能です。このスキルは、`AbstractApplication`の拡張によるアプリケーション作成、`@Action`によるルート定義とCLIアクション、`Context`によるリクエスト状態管理、`Builder`/`Builders`によるネイティブJSONシリアライゼーション、`AbstractData`を用いたデータベース永続化、POJO生成、Server-Sent Events(SSE)、ファイルアップロード、`URLRequest`によるHTTP通信など、幅広いユースケースをカバーします。また、Model Context Protocol(MCP)のネイティブサポートにより、MCPツールとサーバーの作成・デプロイ方法も解説。設定は`application.properties`で管理し、フレームワークのアンチパターンやベストプラクティスに関する表も提供しており、tinystructベースのプロジェクト開発における実践的なリファレンスとして機能します。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/tinystruct-patterns

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

tinystruct 開発パターン

tinystruct Javaフレームワークを使用したモジュール構築のためのアーキテクチャと実装パターン。軽量で高性能なフレームワークであり、CLIとHTTPを同等の地位で扱い、main()メソッドや最小限の設定を必要としません。

核となる原則

CLIとHTTPは同等の市民です。 @Actionでアノテーションされたすべてのメソッドは、修正なしでターミナルとWebブラウザの両方から実行可能であるべきです。この「デュアルモード」機能は、tinystructの中心的な設計思想です。

アクティベーションのタイミング

使用すべきケース

  • AbstractApplicationを拡張して新しいApplicationモジュールを作成する場合。
  • @Actionを使用してルートとコマンドラインアクションを定義する場合。
  • Contextを介してリクエストごとの状態を処理する場合。
  • ネイティブのBuilderおよびBuildersコンポーネントを使用してJSONシリアライゼーションを実行する場合。
  • AbstractData POJOを使用したデータベース永続化を扱う場合。
  • generateコマンドを使用してデータベーステーブルからPOJOを生成する場合。
  • リアルタイムプッシュのためにServer-Sent Events (SSE)を実装する場合。
  • マルチパートデータを使用したファイルアップロードを処理する場合。
  • URLRequestとHTTPHandlerを使用してアウトバウンドHTTPリクエストを行う場合。
  • application.propertiesでデータベース接続やシステム設定を構成する場合。
  • ルーティングの競合(アクション)やCLI引数の解析をデバッグする場合。

仕組み

tinystructフレームワークは、@Actionでアノテーションされた任意のメソッドを、ターミナル環境とWeb環境の両方でルーティング可能なエンドポイントとして扱います。アプリケーションは、init()などのライフサイクルフックとリクエストContextへのアクセスを提供するAbstractApplicationを拡張して作成されます。

ルーティングはActionRegistryによって処理され、パスセグメントをメソッド引数に自動的にマッピングし、依存関係を注入します。データのみのサービスの場合、ゼロ依存フットプリントを維持するために、ネイティブのBuilderおよびBuildersコンポーネントをJSONシリアライゼーションに使用する必要があります。データベース層は、外部ORMライブラリなしでCRUD操作を行うために、XMLマッピングファイルと対になるAbstractData POJOを使用します。

例

基本的なアプリケーション (MyService)

public class MyService extends AbstractApplication {
    @Override
    public void init() {
        this.setTemplateRequired(false); // データ/APIアプリでは.view検索を無効化
    }

    @Override public String version() { return "1.0.0"; }

    @Action("greet")
    public String greet() {
        return "Hello from tinystruct!";
    }

    // パスパラメータ: GET /?q=greet/James  または  bin/dispatcher greet/James
    @Action("greet")
    public String greet(String name) {
        return "Hello, " + name + "!";
    }
}

HTTPモードの曖昧さ回避 (login)

@Action(value = "login", mode = Mode.HTTP_POST)
public String doLogin(Request<?, ?> request) throws ApplicationException {
    request.getSession().setAttribute("userId", "42");
    return "Logged in";
}

ネイティブJSONデータ処理 (Builder + Builders)

import org.tinystruct.data.component.Builder;
import org.tinystruct.data.component.Builders;

@Action("api/data")
public String getData() throws ApplicationException {
    Builders dataList = new Builders();
    Builder item = new Builder();
    item.put("id", 1);
    item.put("name", "James");
    dataList.add(item);

    Builder response = new Builder();
    response.put("status", "success");
    response.put("data", dataList);
    return response.toString(); // {"status":"success","data":[{"id":1,"name":"James"}]}
}

SSE (Server-Sent Events)

import org.tinystruct.http.SSEPushManager;

@Action("sse/connect")
public String connect() {
    return "{\"type\":\"connect\",\"message\":\"Connected to SSE\"}";
}

// 特定のクライアントにプッシュ
String sessionId = getContext().getId();
Builder msg = new Builder();
msg.put("text", "Hello, user!");
SSEPushManager.getInstance().push(sessionId, msg);

// 全クライアントにブロードキャスト
SSEPushManager.getInstance().broadcast(msg);

ファイルアップロード

import org.tinystruct.data.FileEntity;

@Action(value = "upload", mode = Mode.HTTP_POST)
public String upload(Request<?, ?> request) throws ApplicationException {
    List<FileEntity> files = request.getAttachments();
    if (files != null) {
        for (FileEntity file : files) {
            System.out.println("Uploaded: " + file.getFilename());
        }
    }
    return "Upload OK";
}

MCPサーバーとツールの統合

tinystructは、SDKバージョン**1.7.26**以降、Model Context Protocol (MCP)のネイティブサポートを提供します。 MCP API(例:org.tinystruct.mcp.MCPTool、org.tinystruct.mcp.MCPServer、org.tinystruct.mcp.MCPException)は、コア依存関係に直接含まれています:

<dependency>
    <groupId>org.tinystruct</groupId>
    <artifactId>tinystruct</artifactId>
    <version>1.7.26</version>
</dependency>

セキュリティ警告(プロンプトインジェクション): ツールの戻り値は、AIモデルのコンテキストウィンドウに直接フィードバックされます。ツールの戻り文字列に呼び出し元から提供された引数を含める前に、それらを必ず検証およびサニタイズする必要があります。入力をサニタイズしないと、攻撃者が敵対的な指示(プロンプトインジェクション)を挿入し、モデルの動作を上書きする可能性があります。長さ、文字セット、およびnull値を常に検証してください。

MCPツールを作成するには:

  1. org.tinystruct.mcp.MCPToolを拡張します。
  2. @Actionで操作をアノテーションし、arguments配列内で@Argumentを使用してパラメーターを宣言します。
  3. @Argumentのキーと一致する明示的なメソッド引数としてパラメーターを受け入れます。(ツール引数にgetContext().getAttribute(...)を使用しないでください)。
import org.tinystruct.mcp.MCPTool;
import org.tinystruct.mcp.MCPException;
import org.tinystruct.system.annotation.Action;
import org.tinystruct.system.annotation.Argument;

public class MyCustomTool extends MCPTool {
    public MyCustomTool() {
        super("custom", "MCPをデモするカスタムツール");
    }

    @Action(
        value = "custom/hello",
        description = "誰かに挨拶する",
        arguments = {
            @Argument(key = "name", description = "挨拶する名前", type = "string", optional = false)
        }
    )
    public String hello(String name) throws MCPException {
        // セキュリティ:プロンプトインジェクションの脆弱性を防ぐため、
        // モデルに返す前にツール入力を検証/サニタイズします。
        if (name == null || name.length() > 50 || !name.matches("^[a-zA-Z0-9 ]+$")) {
            throw new MCPException("無効な名前が指定されました");
        }
        return "Hello, " + name + "!";
    }
}

MCPサーバーをデプロイするには:

  1. org.tinystruct.mcp.MCPServerを拡張します。
  2. init()をオーバーライドし、this.registerTool()を使用してツールを登録します。フレームワークが@Actionメソッドを自動的にスキャンしてマッピングします。
import org.tinystruct.mcp.MCPServer;

public class MyMCPServer extends MCPServer {
    @Override
    public void init() {
        super.init();
        this.registerTool(new MyCustomTool());
    }

    @Override
    public String version() {
        return "1.0.0";
    }
}

ディスパッチャーを使用してサーバーを実行します:

bin/dispatcher start --import org.tinystruct.system.HttpServer --import com.example.MyMCPServer

設定

設定はsrc/main/resources/application.propertiesで管理されます。

# データベース
driver=org.h2.Driver
database.url=jdbc:h2:~/mydb
database.user=sa
database.password=

# サーバー
default.home.page=hello
server.port=8080

# ロケール
default.language=en_US

# セッション(クラスター環境ではRedis)
# default.session.repository=org.tinystruct.http.RedisSessionRepository
# redis.host=127.0.0.1
# redis.port=6379

アプリケーション内で設定値にアクセスする:

String port = this.getConfiguration("server.port");

レッドフラグとアンチパターン

症状正しいパターン
com.google.gsonまたはcom.fasterxml.jacksonをインポートorg.tinystruct.data.component.Builder / Buildersを使用。
JSON配列にList<Builder>を使用ジェネリック型消去の問題を避けるためにBuildersを使用。
ApplicationRuntimeException: template not foundAPI専用アプリの場合はinit()でsetTemplateRequired(false)を呼び出す。
privateメソッドに@Actionを付与フレームワークによって登録されるには、アクションはpublicである必要があります。
アプリ内でのmain(String[] args)のハードコーディングすべてのモジュールのエントリポイントとしてbin/dispatcherを使用。
手動によるActionRegistry登録自動検出には@Actionアノテーションを推奨。
実行時にアクションが見つからないクラスが--importでインポートされているか、application.propertiesにリストされていることを確認。
CLI引数が見えない--key valueで渡し、getContext().getAttribute("--key")でアクセス。
同じパスの2つのメソッドで、間違った方が実行される曖昧さを回避するために明示的なmode(例:HTTP_GET vs HTTP_POST)を設定。

ベストプラクティス

  1. 粒度の細かいアプリケーション:ロジックを1つの巨大なクラスではなく、より小さく焦点を絞ったアプリケーションに分割します。
  2. init()でのセットアップ:コンストラクタではなく、init()をセットアップ(設定、DB)に活用します。setAction()を呼び出さないでください — @Actionアノテーションを使用します。
  3. モード認識:@ActionのModeパラメータを使用して、機密性の高い操作をCLIのみまたは特定のHTTPメソッドに制限します。
  4. パラメータよりコンテキスト:オプションのCLIフラグの場合、メソッドシグネチャにパラメータを追加する代わりに、getContext().getAttribute("--flag")を使用します。
  5. 非同期イベント:イベントによってトリガーされる重いタスクには、イベントハンドラー内でCompletableFuture.runAsync()を使用します。

テクニカルリファレンス

詳細なガイドはreferences/ディレクトリにあります:

リファレンスソースファイル(内部)

  • src/main/java/org/tinystruct/AbstractApplication.java — ライフサイクルフックを含むコアベースクラス
  • src/main/java/org/tinystruct/system/annotation/Action.java — アノテーションとモード
  • src/main/java/org/tinystruct/application/ActionRegistry.java — ルーティングエンジン
  • src/main/java/org/tinystruct/data/component/Builder.java — JSONオブジェクトシリアライザー
  • src/main/java/org/tinystruct/data/component/Builders.java — JSON配列シリアライザー
  • src/main/java/org/tinystruct/data/component/AbstractData.java — CRUDを含むベースPOJOクラス
  • src/main/java/org/tinystruct/data/Mapping.java — マッピングXMLパーサー
  • src/main/java/org/tinystruct/data/tools/MySQLGenerator.java — POJOジェネレーターのリファレンス
  • src/main/java/org/tinystruct/data/component/FieldType.java — SQLからJavaへの型マッピング
  • src/main/java/org/tinystruct/data/component/Condition.java — 流暢なSQLクエリビルダー
  • src/main/java/org/tinystruct/http/SSEPushManager.java — SSE接続管理
  • src/test/java/org/tinystruct/application/ActionRegistryTest.java — レジストリテストの例
  • src/test/java/org/tinystruct/system/HttpServerHttpModeTest.java — HTTP統合テストのパターン

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

関連スキル