Getting started
Build a link shortener with one use case and expose it as an HTTP API, a CLI and an MCP server.
This guide takes 5 minutes max.
With libmodulor, you write your business logic once, as use cases, with explicit business data types.
From there, you get validation, tests and documentation for free, and you expose the same use cases on any platform (server, CLI, MCP, web, mobile...) without rewriting them.
We are going to write one use case, ShortenURL, that takes a URL and returns a short code.
Then we expose it on three targets without changing a single line of it.
You need Node.js, pnpm and Bun (we use it to run TypeScript directly).
Project
pnpx libmodulor CreateProject --projectName link-shortener
cd link-shortener
Check Create a project for the details.
App
An app groups use cases. Let's create one named Links, with a use case named ShortenURL.
pnpm libmodulor CreateApp --appName Links
pnpm libmodulor CreateUC --appName Links --ucName ShortenURL
The use case is registered in the app's manifest with the Create action.
On a server target, it means it's mounted on POST. That's exactly what we want.
Use case
The CLI generated a placeholder with a foo field. Replace it with a url as input and a code as output.
[๐ src/apps/Links/src/ucds/ShortenURLUCD.ts]
import {
EverybodyUCPolicy,
type FreeTextShort,
SendClientMain,
TFreeTextShort,
TURL,
type UCDef,
type UCInput,
type UCInputFieldValue,
type UCOPIBase,
type URL,
} from 'libmodulor';
import { Manifest } from '../manifest.js';
import { ShortenURLServerMain } from './ShortenURLServerMain.js';
export interface ShortenURLInput extends UCInput {
url: UCInputFieldValue<URL>;
}
export interface ShortenURLOPI0 extends UCOPIBase {
code: FreeTextShort;
}
export const ShortenURLUCD: UCDef<ShortenURLInput, ShortenURLOPI0> = {
io: {
i: {
fields: {
url: {
type: new TURL(),
},
},
},
o: {
parts: {
_0: {
fields: {
code: {
type: new TFreeTextShort(),
},
},
},
},
},
},
lifecycle: {
client: {
main: SendClientMain,
policy: EverybodyUCPolicy,
},
server: {
main: ShortenURLServerMain,
policy: EverybodyUCPolicy,
},
},
metadata: Manifest.ucReg.ShortenURL,
};
TURL is one of the existing data types. It already knows what a valid URL looks like, so you get the validation for free.
The policy is EverybodyUCPolicy : no need to be signed in to shorten a link.
The client simply sends the use case to the server. The server generates the code and saves it.
[๐ src/apps/Links/src/ucds/ShortenURLServerMain.ts]
import { inject, injectable } from 'inversify';
import {
type CryptoManager,
type FreeTextShort,
type UCData,
type UCMain,
type UCMainInput,
type UCManager,
type UCOutput,
UCOutputBuilder,
} from 'libmodulor';
import type { ShortenURLInput, ShortenURLOPI0 } from './ShortenURLUCD.js';
export interface ShortenURLData extends UCData {
code: FreeTextShort;
}
@injectable()
export class ShortenURLServerMain
implements UCMain<ShortenURLInput, ShortenURLOPI0>
{
constructor(
@inject('CryptoManager') private cryptoManager: CryptoManager,
@inject('UCManager') private ucManager: UCManager,
) {}
public async exec({
uc,
}: UCMainInput<ShortenURLInput, ShortenURLOPI0>): Promise<
UCOutput<ShortenURLOPI0>
> {
/// Generate a random code
const code = await this.cryptoManager.randomString(6);
/// Save the code along with the URL
const { aggregateId } = await this.ucManager.persist<
ShortenURLInput,
ShortenURLData,
ShortenURLOPI0
>(uc, { code });
return new UCOutputBuilder<ShortenURLOPI0>()
.add({
code,
id: aggregateId,
})
.get();
}
}
CryptoManager and UCManager are injected. You don't instantiate anything, the target provides the implementations (see Dependency injection).
persist saves the execution in the UCDataStore : the input (url) and the data (code). It's in memory by default, which is fine to get started.
The /// comments are not regular comments. We'll see why right below.
Check Create a use case for everything a use case can do.
Tests
We haven't exposed anything yet, and yet we can already test the use case. Without writing a single test.
pnpm libmodulor TestApp --appName Links
libmodulor knows everything about the use case : its input, its output, its policies, its data types.
So it generates the test suite for you and runs it with vitest.
โ Check > Sources should be valid
โ Check > Folder should be valid
โ Check > Manifest should be valid
โ Check > I18n should be valid
โ Check > index should be valid
โ Check > Use Cases > 'ShortenURL' > should be valid
โ Run > Use Cases > 'ShortenURL' > should execute with auth 'ADMIN' and input 'ALL_WITH_EXAMPLES'
โ Run > Use Cases > 'ShortenURL' > should execute with auth 'ANONYMOUS' and input 'ALL_WITH_EXAMPLES'
โ Run > Use Cases > 'ShortenURL' > should execute with auth 'REGULAR' and input 'ALL_WITH_EXAMPLES'
...
โ Run > Use Cases > 'ShortenURL' > should execute with monkey testing
Tests 16 passed (16)
The use case is executed with every kind of user (anonymous, regular, admin), with valid inputs taken from the data types examples, and with garbage (monkey testing). Outputs are asserted with snapshots, so the next time you change something, you'll know exactly what broke.
It also generates src/apps/Links/README.md, documenting the use case with a sequence diagram.
This is where the /// comments end up :
sequenceDiagram
actor User
User->>+Client: โ๏ธ Fill<br/>url: URL
User->>Client: โฉ๏ธ Submit
Client->>Client: ๐ Check policy "Everybody"
break when any validation fails
Client-->User: show failure
end
Client->>+Server: ๐ค Send<br/>url: URL
Server->>Server: ๐ Check policy "Everybody"
break when any validation fails
Server-->User: show failure
end
Server->>Server: Generate a random code
Server->>Server: Save the code along with the URL
Server-->>-Client: ๐ OK<br/>code: FreeTextShort<br/>id: UUID
Client-->>-User: ๐ OK
Auto tested, auto documented. Check Test an app to go further (flows, seeds, side effects, etc.).
Product
A product assembles apps. It's what end users actually use.
pnpm libmodulor CreateProduct --productName LinkShortener
pnpm libmodulor RegisterApp --appName Links --productName LinkShortener
As the CLI reminds you, spread the app's i18n in the product's i18n.
[๐ src/products/LinkShortener/i18n.ts]
import type { ProductI18n } from 'libmodulor';
import { I18nEN } from 'libmodulor/locales/en';
import { I18n as LinksI18n } from '../../apps/Links/index.js'; // [!code ++]
export const I18n = {
en: {
...I18nEN,
...LinksI18n.en, // [!code ++]
p_desc: '',
p_slogan: '',
},
} satisfies ProductI18n;
Targets
This is where things get interesting. Let's expose the same product on three targets.
pnpm libmodulor CreateTarget --productName LinkShortener --targetName node-express-server
pnpm libmodulor CreateTarget --productName LinkShortener --targetName node-core-cli
pnpm libmodulor CreateTarget --productName LinkShortener --targetName node-mcp-server-stdio
Make sure everything compiles.
pnpm test
All the commands below are run from the root of the project.
node-express-server
We use Express here, but it's just one option. Without touching the use case, you could use instead :
node-core-http-server: plain Node.js HTTP, no frameworknode-hono-server: Hono on Node.jsedge-worker-hono-server: Hono on an edge worker (e.g. Cloudflare Workers)nextjs-server: Next.jsnode-grpc-server: gRPC instead of HTTP
node-core-http-server, node-express-server and node-hono-server can also expose the use cases as an MCP server over HTTP, next to the regular API.
Check Targets for the full list and what each one supports.
Start the server.
bun src/products/LinkShortener/targets/node-express-server/index.ts
Call it with curl.
curl -X POST -H "Content-Type: application/json" -H "X-API-Key: UNSAFE_CHANGE_ME" -d '{}' http://localhost:7443/api/v1/Links_ShortenURL
# โ {"message":"Url must be filled"}
curl -X POST -H "Content-Type: application/json" -H "X-API-Key: UNSAFE_CHANGE_ME" -d '{"url":"not-a-url"}' http://localhost:7443/api/v1/Links_ShortenURL
# โ {"message":"Url must be a valid URL"}
curl -X POST -H "Content-Type: application/json" -H "X-API-Key: UNSAFE_CHANGE_ME" -d '{"url":"https://github.com/c100k/libmodulor"}' http://localhost:7443/api/v1/Links_ShortenURL
# โ
{"parts":{"_0":{"items":[{"code":"jjbp4b","id":"33c02b9e-22c5-4a13-9e04-1909595efc7e"}],"total":1}}}
The X-API-Key is the public API key every server target checks by default. UNSAFE_CHANGE_ME is the default value. As its name says, change it before going anywhere near production (see the settings section of Create a target).
Keep the server running. The two targets below are clients : they send the use case to it.
node-core-cli
bun src/products/LinkShortener/targets/node-core-cli/index.ts Links_ShortenURL --url not-a-url
# โ Url must be a valid URL
bun src/products/LinkShortener/targets/node-core-cli/index.ts Links_ShortenURL --url https://github.com/c100k/libmodulor
# โ
{"parts":{"_0":{"items":[{"code":"fzmo2z","id":"dc61f5d7-6541-407d-b5d8-f5581f6741dc"}],"total":1}}}
The use case is mounted as the Links_ShortenURL command and its url input field as the --url flag.
The input is validated before anything is sent to the server, with the same rules as on the server side.
node-mcp-server-stdio
Register the MCP server in your MCP client. For example in Claude Desktop :
nano ~/Library/Application\ Support/Claude/claude_desktop_config.json
{
"mcpServers": {
"link-shortener": {
"command": "bun",
"args": [
"--tsconfig-override",
"/ABSOLUTE_PATH_TO/link-shortener/tsconfig.json",
"/ABSOLUTE_PATH_TO/link-shortener/src/products/LinkShortener/targets/node-mcp-server-stdio/index.ts"
]
}
}
}
Restart Claude Desktop. Links_ShortenURL is available as a tool.
Can you shorten https://github.com/c100k/libmodulor for me ?
What's next
The use case did not change once. Only the targets did. That's the whole point.
A shortener that cannot resolve its codes is not very useful. Try adding a ResolveURL use case on your own : it takes a code and returns the url.
Then :
- Translate the labels (
Url=>URL) in Translate an app - Expose it in a browser or on mobile like in the Playground
- Bundle it for production in Bundle a target