@molecule/api-web-search-molecule
Provider bond · web-search · API (Node) · v1.1.2 · Apache-2.0
molecule.dev hosted web search provider — web results billed to your molecule project, no vendor account
npm install @molecule/api-web-search-moleculenpm · Source on GitHub · Implements @molecule/api-web-search
How it works
@molecule/api-web-search-molecule is a provider bond on the API (Node) side: it implements the web-search core interface (@molecule/api-web-search) with a concrete vendor or library behind it.
Your code calls the core; you wire this provider once at startup. Swapping vendors later is one line in that wiring, not a rewrite.
Works with: @molecule/api-secrets, @molecule/api-web-search
Secrets: MOLECULE_API_KEY
Reference
molecule.dev hosted web search provider — web results billed to your molecule project, no vendor account
Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit
src/index.tsJSDoc, not this file.
Type
provider
Installation
npm install @molecule/api-web-search-molecule @molecule/api-web-search @molecule/api-secrets
API
Interfaces
MoleculeWebSearchConfig
Options for createProvider. Every field falls back to an env var,
so the zero-argument provider export works from .env alone.
interface MoleculeWebSearchConfig {
/**
* The molecule project API key (`mk_…`), or the sandbox token molecule.dev
* writes for in-IDE apps (`mbk_…`). Defaults to `MOLECULE_API_KEY`.
*/
apiKey?: string
/**
* The hosted services base URL, without a trailing slash. Defaults to
* `MOLECULE_SERVICES_URL`, then `https://api.molecule.dev/api/v1/services`.
*/
servicesUrl?: string
/** Per-request timeout in milliseconds. Default 15000. */
timeoutMs?: number
}
ProcessEnv
Environment variables this provider reads.
interface ProcessEnv {
MOLECULE_API_KEY?: string
MOLECULE_SERVICES_URL?: string
}
Classes
MoleculeServiceError
Error thrown for a refused or failed hosted-service call.
class MoleculeServiceError extends Error {
/** HTTP status from molecule.dev. */
readonly status: number
/** Stable error key from molecule.dev, e.g. `broker.error.budgetExceeded`. */
readonly errorKey: string | undefined
/**
* Create the error.
*
* @param message - Human-readable message.
* @param status - HTTP status.
* @param errorKey - Stable error key, when the service sent one.
* @param cause - The underlying error, if any.
*/
constructor(message: string, status: number, errorKey?: string, cause?: unknown) {
super(message, cause === undefined ? undefined : { cause })
this.name = 'MoleculeServiceError'
this.status = status
this.errorKey = errorKey
}
}
MoleculeWebSearchProvider
Web search provider backed by molecule.dev's hosted service.
class MoleculeWebSearchProvider implements WebSearchProvider {
readonly name = 'molecule'
private readonly apiKey: string
private readonly servicesUrl: string
private readonly timeoutMs: number
/**
* Create the provider.
*
* @param config - Options; each falls back to its env var.
*/
constructor(config: MoleculeWebSearchConfig = {}) {
this.apiKey = config.apiKey ?? process.env.MOLECULE_API_KEY ?? ''
this.servicesUrl = resolveServicesUrl(
config.servicesUrl ?? process.env.MOLECULE_SERVICES_URL ?? DEFAULT_SERVICES_URL,
)
this.timeoutMs = config.timeoutMs ?? 15_000
}
/**
* Search the web.
*
* @param query - The search query (at most 400 characters).
* @param options - Count and localization hints.
* @returns Results in the provider's relevance order.
*/
async search(query: string, options?: WebSearchOptions): Promise<WebSearchResult> {
if (query.length > WEB_SEARCH_SERVICE_LIMITS.maxQueryChars) {
throw new MoleculeServiceError(
`The query is ${query.length} characters. ${HINTS[413]}`,
413,
'hostedServices.error.inputTooLarge',
)
}
return this.request({
query,
...(options?.count !== undefined ? { count: options.count } : {}),
...(options?.country ? { country: options.country } : {}),
...(options?.searchLang ? { searchLang: options.searchLang } : {}),
})
}
/** One POST to the hosted service. */
private async request(body: Record<string, unknown>): Promise<WebSearchResult> {
if (!this.apiKey) {
throw new MoleculeServiceError(
'MOLECULE_API_KEY is not set. Create a project API key on molecule.dev (or with `mlcl apikey create`) and put it in the API .env.',
401,
'hostedServices.error.tokenInvalid',
)
}
const response = await fetch(`${this.servicesUrl}/web-search/search`, {
method: 'POST',
headers: { authorization: `Bearer ${this.apiKey}`, 'content-type': 'application/json' },
body: JSON.stringify(body),
signal: AbortSignal.timeout(this.timeoutMs),
})
const text = await response.text()
let data: unknown
try {
data = text ? JSON.parse(text) : {}
} catch (error) {
// A proxy/gateway error page, not the service: report the status only.
throw new MoleculeServiceError(
`molecule.dev returned ${response.status} with a non-JSON body.`,
response.status,
undefined,
error,
)
}
if (!response.ok) {
const err = data as { error?: string; errorKey?: string }
const hint = HINTS[response.status]
throw new MoleculeServiceError(
`molecule.dev web-search/search failed (${response.status}): ${err.error ?? 'error'}${hint ? ` ${hint}` : ''}`,
response.status,
err.errorKey,
)
}
return data as WebSearchResult
}
}
Functions
createProvider(config)
Create a hosted web search provider.
function createProvider(config?: MoleculeWebSearchConfig): WebSearchProvider
config— Options; each falls back to its env var.
Returns: A WebSearchProvider backed by molecule.dev.
Constants
provider
The provider implementation (wire with setProvider).
const provider: WebSearchProvider
DEFAULT_SERVICES_URL
Default hosted services base URL.
const DEFAULT_SERVICES_URL: 'https://api.molecule.dev/api/v1/services'
WEB_SEARCH_SERVICE_LIMITS
Per-request limits of the hosted service.
const WEB_SEARCH_SERVICE_LIMITS: { readonly maxQueryChars: 400; readonly maxCount: 20 }
webSearchMoleculeSecretDefinitions
Secret definitions required by the molecule.dev hosted web search bond.
const webSearchMoleculeSecretDefinitions: SecretDefinition[]
Core Interface
Implements @molecule/api-web-search interface.
Bond Wiring
Setup function to register this provider with the core interface:
import { setProvider } from '@molecule/api-web-search'
import { provider } from '@molecule/api-web-search-molecule'
export function setupWebSearchMolecule(): void {
setProvider(provider)
}
Injection Notes
Requirements
Peer dependencies:
@molecule/api-web-search>=1.0.0@molecule/api-secrets^1.0.1
Environment Variables
MOLECULE_API_KEY(required) — molecule.dev project API key- Setup: Create one for your project with
mlcl apikey create --project <id> --name <name>(keys start with mk_). - Get it here: https://www.molecule.dev
- Example:
mk_...
- Setup: Create one for your project with
Runtime Dependencies
@molecule/api-web-search@molecule/api-secrets