Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 19 additions & 5 deletions cli/src/main/kotlin/dev/bmcreations/blip/cli/client/ApiClient.kt
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,21 @@ class ApiClient {
private suspend fun ensureToken(): String {
val existing = ConfigManager.getToken()
if (existing != null) {
// Validate
try {
val resp = client.get("$baseUrl/v1/sessions/me") {
// Only a 401 proves the token is invalid. Any other failure (5xx, 429,
// network) must not replace the saved token, or a transient outage
// would log the user out of their account.
val resp = try {
client.get("$baseUrl/v1/sessions/me") {
header("Authorization", "Bearer $existing")
}
if (resp.status == HttpStatusCode.OK) return existing
} catch (_: Exception) {}
} catch (e: Exception) {
throw RuntimeException("Blip API unavailable, try again (could not reach $baseUrl)")
}
when {
resp.status == HttpStatusCode.OK -> return existing
resp.status != HttpStatusCode.Unauthorized ->
throw RuntimeException("Blip API unavailable, try again (HTTP ${resp.status.value})")
}
}

// Create new session
Expand All @@ -42,6 +50,9 @@ class ApiClient {
} catch (e: Exception) {
throw RuntimeException("Cannot connect to $baseUrl — is the server running?")
}
if (!resp.status.isSuccess()) {
throw RuntimeException("Blip API unavailable, try again (HTTP ${resp.status.value})")
}
val result = resp.body<CreateSessionResponse>()
ConfigManager.saveToken(result.token)
return result.token
Expand Down Expand Up @@ -155,6 +166,9 @@ class ApiClient {
}
}

// Note: the session token is passed as a query parameter because browser
// EventSource cannot set an Authorization header. It can end up in server
// and proxy access logs.
fun getSseUrl(inboxId: String): String {
val token = ConfigManager.getToken() ?: ""
return "$baseUrl/v1/inboxes/$inboxId/sse?token=$token"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ class OpenCommand : CliktCommand(name = "open") {
}

val frontendUrl = System.getenv("BLIP_FRONTEND_URL") ?: "https://app.useblip.email"
// The token travels in the URL (the web app strips it after reading it), so it
// can land in browser history and the printed fallback URL below.
val url = "$frontendUrl/app?token=$token"

echo("Opening Blip in browser...")
Expand Down
31 changes: 29 additions & 2 deletions cli/src/main/kotlin/dev/bmcreations/blip/cli/config/Config.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ package dev.bmcreations.blip.cli.config
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import java.io.File
import java.nio.file.Files
import java.nio.file.attribute.PosixFilePermissions
import kotlin.system.exitProcess

@Serializable
data class BlipConfig(
Expand All @@ -19,16 +22,40 @@ object ConfigManager {
if (!configFile.exists()) return BlipConfig()
return try {
json.decodeFromString<BlipConfig>(configFile.readText())
} catch (_: Exception) {
BlipConfig()
} catch (e: Exception) {
// Falling back to an empty config would mint a new session and overwrite
// the saved token, so stop and let the user fix or remove the file.
System.err.println("Error: could not read ${configFile.path}: ${e.message}")
System.err.println("Fix the file or delete it to start a new session.")
exitProcess(1)
}
}

fun save(config: BlipConfig) {
configDir.mkdirs()
restrictPermissions(configDir, "rwx------")
if (!configFile.exists()) {
try {
Files.createFile(
configFile.toPath(),
PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------")),
)
} catch (_: UnsupportedOperationException) {
// Non-POSIX filesystem (Windows); the file is created by writeText below.
}
}
restrictPermissions(configFile, "rw-------")
configFile.writeText(json.encodeToString(BlipConfig.serializer(), config))
}

private fun restrictPermissions(file: File, perms: String) {
try {
Files.setPosixFilePermissions(file.toPath(), PosixFilePermissions.fromString(perms))
} catch (_: UnsupportedOperationException) {
// Windows: no POSIX permissions.
}
}

fun getToken(): String? = load().token

fun saveToken(token: String) {
Expand Down
7 changes: 4 additions & 3 deletions mcp-server/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions mcp-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "@useblip/email",
"mcpName": "io.github.blipemail/email",
"version": "0.1.3",
"description": "MCP server for Blip disposable email — create inboxes, receive emails, extract OTP codes",
"description": "MCP server for Blip disposable email \u2014 create inboxes, receive emails, extract OTP codes",
"type": "module",
"main": "dist/index.js",
"bin": {
Expand All @@ -17,7 +17,8 @@
"prepublishOnly": "npm run build"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.27.1"
"@modelcontextprotocol/sdk": "~1.27.1",
"zod": "~4.3.6"
},
"devDependencies": {
"typescript": "^5.7.0",
Expand Down
127 changes: 112 additions & 15 deletions mcp-server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import { createRequire } from "node:module";

// dist/index.js -> ../package.json
const pkg = createRequire(import.meta.url)("../package.json") as { version: string };

const API_URL = process.env.BLIP_API_URL || "https://api.useblip.email";
const API_KEY = process.env.BLIP_API_KEY || "";
Expand All @@ -21,11 +25,72 @@ if (!/^blip_[a-zA-Z0-9_]+$/.test(API_KEY)) {
process.exit(1);
}

class BlipApiError extends Error {
constructor(
message: string,
readonly status: number,
readonly retryAfterSeconds?: number
) {
super(message);
this.name = "BlipApiError";
}
}

function errorDetail(body: string): string {
try {
const parsed = JSON.parse(body) as { message?: unknown };
if (typeof parsed.message === "string" && parsed.message) return parsed.message;
} catch {
// not JSON
}
return body.trim();
}

function parseRetryAfter(value: string | null): number | undefined {
if (!value) return undefined;
const seconds = Number(value);
if (Number.isFinite(seconds) && seconds >= 0) return seconds;
const date = Date.parse(value);
if (!Number.isNaN(date)) return Math.max(0, Math.ceil((date - Date.now()) / 1000));
return undefined;
}

function describeError(
status: number,
method: string,
path: string,
detail: string,
retryAfter?: number
): string {
const upgrade =
"This feature needs a higher Blip plan. Upgrade at https://useblip.email/app.";
const invalidKey =
"Invalid or expired API key. Check BLIP_API_KEY, or create a new key at https://useblip.email/app.";
switch (status) {
case 401:
return invalidKey;
case 402:
return `${upgrade}${detail ? ` (${detail})` : ""}`;
case 403:
// The server also uses 403 for "Access denied" on resources the key doesn't own.
return /plan|tier|upgrade|pro\b|agent/i.test(detail)
? `${upgrade}${detail ? ` (${detail})` : ""}`
: `Access denied${detail ? ` (${detail})` : ""}. The API key may be invalid or expired, or it doesn't own this resource.`;
case 429:
return retryAfter !== undefined
? `Rate limited by the Blip API. Retry after ${retryAfter} seconds.`
: "Rate limited by the Blip API. Wait a moment and retry.";
default:
return `Blip API error ${status} on ${method} ${path}: ${detail}`;
}
}

async function blipFetch(
path: string,
options: RequestInit = {}
): Promise<unknown> {
const url = `${API_URL}${path}`;
const method = options.method || "GET";
const res = await fetch(url, {
...options,
headers: {
Expand All @@ -36,17 +101,28 @@ async function blipFetch(
});

if (!res.ok) {
const body = await res.text();
throw new Error(`Blip API error ${res.status} on ${options.method || "GET"} ${path}: ${body}`);
const detail = errorDetail(await res.text());
const retryAfter = parseRetryAfter(res.headers.get("Retry-After"));
throw new BlipApiError(
describeError(res.status, method, path, detail, retryAfter),
res.status,
retryAfter
);
}

if (res.status === 204) return null;
return res.json();
}

// 5xx, 429 and network failures (fetch rejects) may succeed on a later attempt.
function isTransient(err: unknown): boolean {
if (err instanceof BlipApiError) return err.status === 429 || err.status >= 500;
return err instanceof TypeError;
}

const server = new McpServer({
name: "blip",
version: "0.1.2",
version: pkg.version,
});

// --- Tools ---
Expand Down Expand Up @@ -146,29 +222,50 @@ server.tool(
async ({ inbox_id, timeout_seconds }) => {
const timeout = Math.min(timeout_seconds ?? 60, 300);
const deadline = Date.now() + timeout * 1000;
const interval = 2000;
const baseDelay = 2000;
const maxDelay = 10000;
let failures = 0;
let lastError: unknown;

while (Date.now() < deadline) {
const result = (await blipFetch(`/v1/inboxes/${inbox_id}`)) as {
emails?: { id: string }[];
};

if (result?.emails && result.emails.length > 0) {
// Return the full detail of the most recent email
const email = await blipFetch(`/v1/emails/${result.emails[0].id}`);
return {
content: [{ type: "text", text: JSON.stringify(email, null, 2) }],
let delay = baseDelay;
try {
const result = (await blipFetch(`/v1/inboxes/${inbox_id}`)) as {
emails?: { id: string }[];
};

if (result?.emails && result.emails.length > 0) {
// Return the full detail of the most recent email
const email = await blipFetch(`/v1/emails/${result.emails[0].id}`);
return {
content: [{ type: "text", text: JSON.stringify(email, null, 2) }],
};
}
failures = 0;
} catch (err) {
if (!isTransient(err)) throw err;
lastError = err;
failures++;
delay = Math.min(baseDelay * 2 ** (failures - 1), maxDelay);
if (err instanceof BlipApiError && err.retryAfterSeconds !== undefined) {
delay = Math.max(delay, err.retryAfterSeconds * 1000);
}
}

await new Promise((resolve) => setTimeout(resolve, interval));
const remaining = deadline - Date.now();
if (remaining <= 0) break;
await new Promise((resolve) => setTimeout(resolve, Math.min(delay, remaining)));
}

return {
content: [
{
type: "text",
text: `No email received in inbox ${inbox_id} after ${timeout} seconds.`,
text:
`No email received in inbox ${inbox_id} after ${timeout} seconds.` +
(lastError
? ` The last poll failed with a transient error: ${(lastError as Error).message}`
: ""),
},
],
};
Expand Down
Loading