tinystruct-patterns
affaan-m/ecc
Expert guidance for tinystruct Java framework development with dual-mode CLI/HTTP routing.
What is tinystruct-patterns?
Provides patterns and best practices for building applications with tinystruct, a lightweight Java framework that treats CLI and HTTP as equal citizens. Use this skill when creating Application classes, defining @Action routes, handling database persistence, implementing SSE, file uploads, or integrating with the Model Context Protocol (MCP).
- Create Application modules by extending AbstractApplication with @Action-annotated methods
- Route requests to both CLI and HTTP endpoints without modification using the dual-mode philosophy
- Serialize data using native Builder and Builders components for zero-dependency JSON handling
- Persist data with AbstractData POJOs and XML mapping files for CRUD operations
- Implement Server-Sent Events (SSE) for real-time push notifications to clients
- Handle multipart file uploads and outbound HTTP requests via URLRequest and HTTPHandler
How to install tinystruct-patterns
npx skills add null --skill tinystruct-patterns- Java development environment with Maven or Gradle
- tinystruct SDK version 1.7.26 or later (for MCP support)
- Basic understanding of Java annotations and dependency injection
How to use tinystruct-patterns
- 1.Extend AbstractApplication and override init() to configure your module
- 2.Define routable methods using @Action annotations with optional path parameters
- 3.Use Builder/Builders for JSON serialization or AbstractData POJOs for database operations
- 4.For HTTP-only actions, specify mode = Mode.HTTP_POST or Mode.HTTP_GET in @Action
- 5.Implement SSE by using SSEPushManager.getInstance() to push messages to clients
- 6.For MCP tools, extend MCPTool and use @Argument annotations to declare parameters
- 7.Register tools in an MCPServer subclass and deploy via the dispatcher
Use cases
- Building REST APIs and CLI tools from the same codebase without duplication
- Creating real-time applications with SSE push notifications to connected clients
- Implementing file upload endpoints that work identically from web and terminal interfaces
- Developing MCP-compatible tools for integration with Claude Code and other AI agents
- Handling session-based authentication that works across both HTTP and CLI modes
- Java developers building dual-mode CLI/HTTP applications
- Backend engineers creating REST APIs with minimal configuration
- Teams developing AI agent tools using the Model Context Protocol
- Developers working on the tinystruct framework codebase itself
tinystruct-patterns FAQ
CLI and HTTP are equal citizens. Every @Action method should be runnable from both terminal and web browser without modification, eliminating code duplication.
Use the mode parameter in @Action: @Action(value = "login", mode = Mode.HTTP_POST) to restrict the action to specific protocols.
No. tinystruct provides native Builder and Builders components for zero-dependency JSON serialization, which is the recommended approach.
Always validate and sanitize caller-supplied arguments before returning them in the tool's response string. Check length, character sets, and nullity to prevent adversarial instructions from reaching the model.
Yes. Extend AbstractData for POJO persistence, use XML mapping files for CRUD operations, and generate POJOs from database tables using the generate command.
Full instructions (SKILL.md)
Source of truth, from affaan-m/ecc.
name: tinystruct-patterns description: Expert guidance for developing with the tinystruct Java framework. Use when working on the tinystruct codebase or any project built on tinystruct — including creating Application classes, @Action-mapped routes, unit tests, ActionRegistry, HTTP/CLI dual-mode handling, the built-in HTTP server, the event system, JSON with Builder/Builders, database persistence with AbstractData, POJO generation, Server-Sent Events (SSE), file uploads, and outbound HTTP networking. metadata: origin: ECC
tinystruct Development Patterns
Architecture and implementation patterns for building modules with the tinystruct Java framework – a lightweight, high-performance framework that treats CLI and HTTP as equal citizens, requiring no main() method and minimal configuration.
Core Principle
CLI and HTTP are equal citizens. Every method annotated with @Action should ideally be runnable from both a terminal and a web browser without modification. This "dual-mode" capability is the core design philosophy of tinystruct.
When to Activate
When to Use
- Creating new
Applicationmodules by extendingAbstractApplication. - Defining routes and command-line actions using
@Action. - Handling per-request state via
Context. - Performing JSON serialization using the native
BuilderandBuilderscomponents. - Working with database persistence via
AbstractDataPOJOs. - Generating POJOs from database tables using the
generatecommand. - Implementing Server-Sent Events (SSE) for real-time push.
- Handling file uploads via multipart data.
- Making outbound HTTP requests with
URLRequestandHTTPHandler. - Configuring database connections or system settings in
application.properties. - Debugging routing conflicts (Actions) or CLI argument parsing.
How It Works
The tinystruct framework treats any method annotated with @Action as a routable endpoint for both terminal and web environments. Applications are created by extending AbstractApplication, which provides core lifecycle hooks like init() and access to the request Context.
Routing is handled by the ActionRegistry, which automatically maps path segments to method arguments and injects dependencies. For data-only services, the native Builder and Builders components should be used for JSON serialization to maintain a zero-dependency footprint. The database layer uses AbstractData POJOs paired with XML mapping files for CRUD operations without external ORM libraries.
Examples
Basic Application (MyService)
public class MyService extends AbstractApplication {
@Override
public void init() {
this.setTemplateRequired(false); // Disable .view lookup for data/API apps
}
@Override public String version() { return "1.0.0"; }
@Action("greet")
public String greet() {
return "Hello from tinystruct!";
}
// Path parameter: GET /?q=greet/James OR bin/dispatcher greet/James
@Action("greet")
public String greet(String name) {
return "Hello, " + name + "!";
}
}
HTTP Mode Disambiguation (login)
@Action(value = "login", mode = Mode.HTTP_POST)
public String doLogin(Request<?, ?> request) throws ApplicationException {
request.getSession().setAttribute("userId", "42");
return "Logged in";
}
Native JSON Data Handling (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\"}";
}
// Push to a specific client
String sessionId = getContext().getId();
Builder msg = new Builder();
msg.put("text", "Hello, user!");
SSEPushManager.getInstance().push(sessionId, msg);
// Broadcast to all
// Broadcast to all
SSEPushManager.getInstance().broadcast(msg);
File Upload
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 Server and Tools Integration
tinystruct provides native support for the Model Context Protocol (MCP) starting with SDK version 1.7.26.
The MCP APIs (e.g., org.tinystruct.mcp.MCPTool, org.tinystruct.mcp.MCPServer, org.tinystruct.mcp.MCPException) are included directly in the core dependency:
<dependency>
<groupId>org.tinystruct</groupId>
<artifactId>tinystruct</artifactId>
<version>1.7.26</version>
</dependency>
SECURITY WARNING (Prompt Injection): Tool return values are fed directly back into the AI model's context window. You MUST validate and sanitize all caller-supplied arguments before including them in the tool's return string. Failure to sanitize inputs can allow an attacker to inject adversarial instructions (Prompt Injection) that override the model's behavior. Always validate length, character sets, and nullity.
To create an MCP Tool:
- Extend
org.tinystruct.mcp.MCPTool. - Annotate operations with
@Actionand declare parameters using@Argumentwithin theargumentsarray. - Accept parameters as explicit method arguments matching the keys in
@Argument. (Do not usegetContext().getAttribute(...)for tool arguments).
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 {
// SECURITY: Validate/sanitize tool inputs before returning to the model
// to prevent prompt injection vulnerabilities.
if (name == null || name.length() > 50 || !name.matches("^[a-zA-Z0-9 ]+$")) {
throw new MCPException("Invalid name provided");
}
return "Hello, " + name + "!";
}
}
To deploy an MCP Server:
- Extend
org.tinystruct.mcp.MCPServer. - Override
init()and register your tools usingthis.registerTool(). The framework automatically scans and maps the@Actionmethods.
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";
}
}
Run the server via the dispatcher:
bin/dispatcher start --import org.tinystruct.system.HttpServer --import com.example.MyMCPServer
Configuration
Settings are managed in src/main/resources/application.properties.
# Database
driver=org.h2.Driver
database.url=jdbc:h2:~/mydb
database.user=sa
database.password=
# Server
default.home.page=hello
server.port=8080
# Locale
default.language=en_US
# Session (Redis for clustered environments)
# default.session.repository=org.tinystruct.http.RedisSessionRepository
# redis.host=127.0.0.1
# redis.port=6379
Access config values in your application:
String port = this.getConfiguration("server.port");
Red Flags & Anti-patterns
| Symptom | Correct Pattern |
|---|---|
Importing com.google.gson or com.fasterxml.jackson | Use org.tinystruct.data.component.Builder / Builders. |
Using List<Builder> for JSON arrays | Use Builders to avoid generic type erasure issues. |
ApplicationRuntimeException: template not found | Call setTemplateRequired(false) in init() for API-only apps. |
Annotating private methods with @Action | Actions must be public to be registered by the framework. |
Hardcoding main(String[] args) in apps | Use bin/dispatcher as the entry point for all modules. |
Manual ActionRegistry registration | Prefer the @Action annotation for automatic discovery. |
| Action not found at runtime | Ensure class is imported via --import or listed in application.properties. |
| CLI arg not visible | Pass with --key value; access via getContext().getAttribute("--key"). |
| Two methods same path, wrong one fires | Set explicit mode (e.g., HTTP_GET vs HTTP_POST) to disambiguate. |
Best Practices
- Granular Applications: Break logic into smaller, focused applications rather than one monolithic class.
- Setup in
init(): Leverageinit()for setup (config, DB) rather than the constructor. Do NOT callsetAction()— use@Actionannotation. - Mode Awareness: Use the
Modeparameter in@Actionto restrict sensitive operations toCLIonly or specific HTTP methods. - Context over Params: For optional CLI flags, use
getContext().getAttribute("--flag")rather than adding parameters to the method signature. - Asynchronous Events: For heavy tasks triggered by events, use
CompletableFuture.runAsync()inside the event handler.
Technical Reference
Detailed guides are available in the references/ directory:
- Architecture & Config — Abstractions, Package Map, Properties
- Routing & @Action — Annotation details, Modes, Parameters
- Data Handling — Builder, Builders, JSON serialization & parsing
- Database Persistence — AbstractData POJOs, CRUD, mapping XML, POJO generation
- System & Usage — Context, Sessions, SSE, File Uploads, Events, Networking
- Testing Patterns — JUnit 5 unit and HTTP integration testing
Reference Source Files (Internal)
src/main/java/org/tinystruct/AbstractApplication.java— Core base class with lifecycle hookssrc/main/java/org/tinystruct/system/annotation/Action.java— Annotation & Modessrc/main/java/org/tinystruct/application/ActionRegistry.java— Routing Enginesrc/main/java/org/tinystruct/data/component/Builder.java— JSON object serializersrc/main/java/org/tinystruct/data/component/Builders.java— JSON array serializersrc/main/java/org/tinystruct/data/component/AbstractData.java— Base POJO class with CRUDsrc/main/java/org/tinystruct/data/Mapping.java— Mapping XML parsersrc/main/java/org/tinystruct/data/tools/MySQLGenerator.java— POJO generator referencesrc/main/java/org/tinystruct/data/component/FieldType.java— SQL-to-Java type mappingssrc/main/java/org/tinystruct/data/component/Condition.java— Fluent SQL query buildersrc/main/java/org/tinystruct/http/SSEPushManager.java— SSE connection managementsrc/test/java/org/tinystruct/application/ActionRegistryTest.java— Registry test examplessrc/test/java/org/tinystruct/system/HttpServerHttpModeTest.java— HTTP integration test patterns
Related skills
More from affaan-m/ecc and the wider catalog.
token-budget-advisor
Let users choose response depth upfront by estimating token budget before answering.
ui-demo
Record polished UI demo videos with Playwright, cursor overlay, and natural pacing.
ui-to-vue
Batch-convert UI design screenshots into Vue 3 Composition API components with Vant, Element Plus, or Ant Design Vue.
uncloud
Manage decentralised self-hosted Docker clusters with WireGuard mesh, Caddy ingress, and peer-based orchestration.
unified-memory
Agent skill from affaan-m/ecc.
unified-notifications-ops
Consolidate GitHub, Linear, and desktop alerts into one operator-driven notification workflow with severity routing and deduplication.