Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

10.5 KB
Raw Blame
use super::models::{
    CatalogEntry, CatalogPage, ConnectApp, ConnectToken, ConnectorOverlay, MacroUserIdStr,
    McpServer, PipedreamAccount, PipedreamConnection,
};

/// The catalog apps that connect through the native MCP stack instead of
/// Pipedream.
pub trait ConnectorOverlays: Send + Sync + 'static {
    /// Every overlaid app.
    fn overlays(&self) -> impl Future<Output = anyhow::Result<Vec<ConnectorOverlay>>> + Send;

    /// The overlay for `app_slug`, if the app is overlaid.
    fn overlay(
        &self,
        app_slug: &str,
    ) -> impl Future<Output = anyhow::Result<Option<ConnectorOverlay>>> + Send;
}

/// A user's connections to overlaid apps, which live on the native MCP stack
/// rather than in Pipedream.
pub trait OverlayConnections: Send + Sync + 'static {
    /// The display name of `user`'s enabled, authorized connection to
    /// `overlay`'s MCP server, if they hold one.
    fn connected_name(
        &self,
        user: &MacroUserIdStr<'static>,
        overlay: &ConnectorOverlay,
    ) -> impl Future<Output = anyhow::Result<Option<String>>> + Send;
}

/// Cross-user lookup for background integrations that follow a connected app.
pub trait AppConnections: Send + Sync + 'static {
    /// Every user's enabled connection to `app_slug`.
    fn list_enabled_for_app(
        &self,
        app_slug: &str,
    ) -> impl Future<Output = anyhow::Result<Vec<PipedreamConnection>>> + Send;
}

/// Port for persisting Pipedream-connected apps, keyed by user and app slug.
///
/// Reads never return a connection to an overlaid app (see
/// [`ConnectorOverlays`]): once an app is overlaid, a Pipedream grant for it
/// stops reaching tools, imports, and sandboxes everywhere at once.
pub trait ConnectionStore: Send + Sync + 'static {
    /// Error type for store operations.
    type Err: Send + std::fmt::Debug;

    /// Persist a record, overwriting any existing entry for the same user and app.
    fn save(
        &self,
        record: &PipedreamConnection,
    ) -> impl Future<Output = Result<(), Self::Err>> + Send;

    /// Load a record for a user and app slug. Returns `None` if not stored.
    fn load(
        &self,
        user_id: &MacroUserIdStr<'static>,
        app_slug: &str,
    ) -> impl Future<Output = Result<Option<PipedreamConnection>, Self::Err>> + Send;

    /// Delete a record for a user and app slug.
    fn delete(
        &self,
        user_id: &MacroUserIdStr<'static>,
        app_slug: &str,
    ) -> impl Future<Output = Result<(), Self::Err>> + Send;

    /// List all stored records for a user.
    fn list(
        &self,
        user_id: &MacroUserIdStr<'static>,
    ) -> impl Future<Output = Result<Vec<PipedreamConnection>, Self::Err>> + Send;
}

/// Port for opening a live MCP connection for a connected app.
///
/// The single implementation connects to Pipedream's remote MCP server,
/// scoped to the record's user and app; Pipedream injects the account's
/// credentials server-side, so no tokens ever pass through here.
pub trait McpConnection: Send + Sync + 'static {
    /// Whether this deployment has the configuration needed to connect.
    fn is_configured(&self) -> bool;

    /// Connect to the MCP server serving `record`'s app for `record.user_id`.
    fn connect(
        &self,
        record: &PipedreamConnection,
    ) -> impl Future<Output = anyhow::Result<McpServer>> + Send;
}

/// An unconfigured deployment: `None` connects nothing, so toolsets built
/// before Pipedream is configured degrade to empty instead of erroring at
/// composition time.
impl<P: McpConnection> McpConnection for Option<std::sync::Arc<P>> {
    fn is_configured(&self) -> bool {
        self.as_ref()
            .is_some_and(|connection| connection.is_configured())
    }

    async fn connect(&self, record: &PipedreamConnection) -> anyhow::Result<McpServer> {
        match self {
            Some(connection) => connection.connect(record).await,
            None => anyhow::bail!("Pipedream is not configured"),
        }
    }
}

/// Port for Pipedream Connect: managed auth for MCP connectors.
///
/// Pipedream owns the whole account lifecycle — the consent flow (hosted
/// Connect UI), credential storage, and token refresh. The domain only ever
/// sees short-lived Connect tokens and account metadata.
pub trait PipedreamConnect: Send + Sync + 'static {
    /// Create a short-lived Connect token for `external_user_id` (our user
    /// ID), used by the frontend to open the hosted Connect UI.
    fn create_connect_token(
        &self,
        external_user_id: &str,
    ) -> impl Future<Output = anyhow::Result<ConnectToken>> + Send;

    /// Fetch a connected account's metadata. Returns `None` if Pipedream
    /// doesn't know the account ID.
    fn get_account(
        &self,
        account_id: &str,
    ) -> impl Future<Output = anyhow::Result<Option<PipedreamAccount>>> + Send;

    /// List the accounts connected for `external_user_id` (our user ID) to
    /// `app_slug`, in no particular order.
    fn list_accounts(
        &self,
        external_user_id: &str,
        app_slug: &str,
    ) -> impl Future<Output = anyhow::Result<Vec<PipedreamAccount>>> + Send;

    /// Delete a connected account from Pipedream (revoking our copy of the
    /// grant).
    fn delete_account(&self, account_id: &str) -> impl Future<Output = anyhow::Result<()>> + Send;
}

/// Port for Macro Connect's connect flow: Connect owns the consent flow,
/// the grant, and refresh, like Pipedream Connect, but Macro owns the OAuth
/// apps. Apps are addressed by the Pipedream slug they replace.
pub trait MacroConnect: Send + Sync + 'static {
    /// Whether every connector call for `user_id` goes through Connect, with
    /// no Pipedream at all: Connect is configured and the `macro-connect`
    /// rollout is on for them. Otherwise everything stays on Pipedream.
    fn connect_only(&self, user_id: &MacroUserIdStr<'static>) -> impl Future<Output = bool> + Send;

    /// The Connect app standing in for `app_slug`, or `None` when Connect
    /// does not serve it (or is not configured).
    fn app_for_slug(
        &self,
        app_slug: &str,
    ) -> impl Future<Output = anyhow::Result<Option<ConnectApp>>> + Send;

    /// Start a browser connect session for `user_id` and return the URL to
    /// open. Connect redirects back to Macro when consent finishes.
    fn create_connect_session(
        &self,
        user_id: &MacroUserIdStr<'static>,
        app: &ConnectApp,
    ) -> impl Future<Output = anyhow::Result<String>> + Send;

    /// Whether `user_id` holds a usable connection to `app_id`.
    fn is_connected(
        &self,
        user_id: &MacroUserIdStr<'static>,
        app_id: &str,
    ) -> impl Future<Output = anyhow::Result<bool>> + Send;

    /// Delete `user_id`'s connection to `app_id` from Connect.
    fn delete_connection(
        &self,
        user_id: &MacroUserIdStr<'static>,
        app_id: &str,
    ) -> impl Future<Output = anyhow::Result<()>> + Send;
}

/// Port for browsing the directory of connectable apps. Lookups are for a
/// user because the directory is theirs: Connect's catalog for a user on
/// Connect (see [`MacroConnect::connect_only`]), Pipedream's otherwise.
pub trait ConnectorDirectory: Send + Sync + 'static {
    /// Search the directory.
    ///
    /// `search` filters apps by name; `None` browses everything. `cursor` is
    /// the opaque pagination cursor from a previous page. Implementations
    /// return entries most-popular-first, and only apps that can actually be
    /// connected and used (i.e. apps with an auth flow and at least one
    /// action to expose as a tool) and that the catalog doesn't hide.
    fn search(
        &self,
        user_id: &MacroUserIdStr<'static>,
        search: Option<&str>,
        cursor: Option<&str>,
        limit: u32,
    ) -> impl Future<Output = anyhow::Result<CatalogPage>> + Send;

    /// Look up one app by its name slug.
    ///
    /// `Ok(None)` when Pipedream has no connectable app under that exact slug:
    /// unknown, an app with no auth flow (nothing to connect), or one the
    /// catalog hides. A lookup that cannot be completed is an error, not a
    /// miss.
    fn retrieve(
        &self,
        user_id: &MacroUserIdStr<'static>,
        app_slug: &str,
    ) -> impl Future<Output = anyhow::Result<Option<CatalogEntry>>> + Send;
}

/// Read an app's advertised capabilities without invoking any of its tools.
pub trait ConnectorCapabilities: Send + Sync + 'static {
    /// List tools, including for apps this user has not connected yet.
    fn tools(
        &self,
        user_id: &MacroUserIdStr<'static>,
        app_slug: &str,
    ) -> impl Future<Output = anyhow::Result<Vec<super::service::discovery::ConnectorTool>>> + Send;
}

/// A connected app's answer, relayed through the proxy whatever its status.
/// Never log the body: some apps return secrets (webhook registration).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProxyResponse {
    /// The HTTP status.
    pub status: http::StatusCode,
    /// The app's response headers.
    pub headers: http::HeaderMap,
    /// The response body.
    pub body: String,
}

impl ProxyResponse {
    /// How long the app asked callers to wait, from a `Retry-After` header
    /// in seconds.
    pub fn retry_after(&self) -> Option<std::time::Duration> {
        self.headers
            .get(http::header::RETRY_AFTER)?
            .to_str()
            .ok()?
            .trim()
            .parse()
            .ok()
            .map(std::time::Duration::from_secs)
    }
}

/// Port for calling a connected app's own API with the account's
/// credentials, which Pipedream injects server-side.
pub trait ConnectedAppProxy: Send + Sync + 'static {
    /// Send a request to the connected app's API on behalf of `connection`'s
    /// account.
    ///
    /// `url` is absolute (e.g. `https://api.notion.com/v1/search`).
    /// `headers` are upstream headers, never `Authorization`. A non-2xx
    /// answer from the app is a response, not an error, so callers can read
    /// its status and back off.
    fn proxy(
        &self,
        connection: &PipedreamConnection,
        method: http::Method,
        url: &str,
        headers: &http::HeaderMap,
        body: Option<&serde_json::Value>,
    ) -> impl Future<Output = anyhow::Result<ProxyResponse>> + Send;
}

/// Whether the `macro-connect` rollout is on for a user: every connector
/// call for them goes through Macro Connect instead of Pipedream. Hosts read
/// the feature flag here; a failed read must answer `false`.
pub type ConnectRollout = std::sync::Arc<
    dyn Fn(MacroUserIdStr<'static>) -> std::pin::Pin<Box<dyn Future<Output = bool> + Send>>
        + Send
        + Sync,
>;