Communitygithub.com

tinystruct 開發模式

使用 tinystruct Java 框架開發的專家指南。適用於建置 tinystruct 程式庫或任何基於 tinystruct 的專案——包括建立 Application 類別、@Action 對應路由、單元測試、ActionRegistry、HTTP/CLI 雙模式處理、內建 HTTP 伺服器、事件系統、搭配 Builder/Builders 的 JSON、使用 AbstractData 的資料庫持久化、POJO 生成、伺服器傳送事件 (SSE)、檔案上傳以及對外 HTTP 網路請求。

tinystruct 開發模式 是什麼?

tinystruct 是一個輕量級、高效能的 Java 框架,其核心設計理念是「CLI 與 HTTP 為平等公民」,每個以 @Action 標註的方法,無需修改即可同時從終端和網頁瀏覽器執行。此技能適用於開發者建立新的 Application 模組、定義路由與命令列動作、處理請求狀態、進行 JSON 序列化、實現資料庫持久化、生成 POJO、實施 SSE 即時推送、處理檔案上傳,以及進行對外 HTTP 請求。框架支援透過 AbstractApplication 建立應用程式,利用 ActionRegistry 自動對應路由,並內建 MCP (Model Context Protocol) 工具與伺服器整合,讓 AI 代理可直接呼叫框架功能。開發者應避免引入外部 JSON 函式庫,並遵循在 init() 中設定、使用 @Action 而非手動註冊等最佳實踐,以避免常見的反模式錯誤。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/tinystruct-patterns

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

tinystruct 開發模式 是做什麼的?

使用 tinystruct Java 框架建置模組的架構與實作模式——這是一個輕量級、高效能的框架,將 CLI 與 HTTP 視為平等公民,無需 main() 方法且設定極簡。

核心原則

CLI 與 HTTP 是平等公民。 每個用 @Action 標註的方法,理想上應能不經修改即同時從終端和網頁瀏覽器執行。這種「雙模式」能力是 tinystruct 的核心設計理念。

啟動時機

何時使用

  • 透過擴充 AbstractApplication 建立新的 Application 模組。
  • 使用 @Action 定義路由與命令列動作。
  • 透過 Context 處理每個請求的狀態。
  • 使用原生 Builder 和 Builders 元件進行 JSON 序列化。
  • 透過 AbstractData POJO 進行資料庫持久化。
  • 使用 generate 命令從資料庫表格生成 POJO。
  • 實作伺服器傳送事件 (SSE) 以實現即時推送。
  • 透過 multipart 資料處理檔案上傳。
  • 使用 URLRequest 和 HTTPHandler 發起對外 HTTP 請求。
  • 在 application.properties 中設定資料庫連線或系統設定。
  • 除錯路由衝突 (Actions) 或 CLI 參數解析。

運作方式

tinystruct 框架將任何以 @Action 標註的方法視為終端和網頁環境均可路由的端點。應用程式透過擴充 AbstractApplication 建立,該類別提供核心生命週期鉤子如 init() 以及對請求 Context 的存取。

路由由 ActionRegistry 處理,它會自動將路徑區段對應到方法參數並注入依賴。對於純資料服務,應使用原生 Builder 和 Builders 元件進行 JSON 序列化,以維持零依賴的足跡。資料庫層使用 AbstractData POJO 搭配 XML 對應檔案進行 CRUD 操作,無需外部 ORM 函式庫。

範例

基本應用程式 (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 (伺服器傳送事件)

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 開始原生支援模型上下文協定 (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 模型的上下文視窗。在將工具回傳字串包含進回應之前,你必須驗證並清理所有呼叫者提供的引數。未清理輸入可能讓攻擊者注入惡意指令(提示注入),覆蓋模型的行為。務必驗證長度、字元集和空值。

建立 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", "A custom tool for demonstrating MCP");
    }

    @Action(
        value = "custom/hello",
        description = "Say hello to someone",
        arguments = {
            @Argument(key = "name", description = "The name to greet", 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";
    }
}

透過 dispatcher 執行伺服器:

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。
使用 List<Builder> 處理 JSON 陣列使用 Builders 以避免泛型型別擦除問題。
ApplicationRuntimeException: template not found對於純 API 應用程式,在 init() 中呼叫 setTemplateRequired(false)。
將 private 方法標註 @ActionAction 必須是 public 才能被框架註冊。
在應用程式中硬編碼 main(String[] args)所有模組都使用 bin/dispatcher 作為進入點。
手動 ActionRegistry 註冊傾向使用 @Action 註解進行自動發現。
執行時期找不到 Action確保類別已透過 --import 匯入或列在 application.properties 中。
CLI 引數不可見使用 --key value 傳遞;透過 getContext().getAttribute("--key") 存取。
兩個方法相同路徑,錯誤的方法被觸發設定明確的 mode(例如 HTTP_GET 與 HTTP_POST)來區別。

最佳實踐

  1. 細粒度應用程式:將邏輯拆分為較小、聚焦的應用程式,而不是一個單一的巨型類別。
  2. 在 init() 中設定:利用 init() 進行設定(設定、資料庫),而不是在建構子中。請不要呼叫 setAction()——使用 @Action 註解。
  3. 模式感知:使用 @Action 中的 Mode 參數將敏感操作限制為僅 CLI 或特定的 HTTP 方法。
  4. Context 優於參數:對於選擇性的 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.

相關技能