# Getting Started

Cognition provides a streamlined environment for running cognitive experiments online. This guide will walk you through the foundational steps to set up, code, and deploy your experiments using Cognition.

#### **1. Setting Up Your Account**

Before diving into experiments, create your Cognition account:

* Navigate to the Cognition homepage.
* Click on "Create an account" to initiate the registration process.
* Fill out the required fields: name, email, and password.
* Once registered, you'll have access to Cognition’s dashboard and the suite of tools available.

#### **2. Coding Your Task with jsPsych**

jsPsych is at the core of task creation within Cognition. Here’s how to get started:

* Open the Cognition online code editor.
* Code your task using the jsPsych library. If you're new to jsPsych, consider starting with available templates.
* For users with pre-existing tasks on GitHub, import functionality is available.

#### **3. Experiment Sharing & Deployment**

Once your task is coded, deployment is straightforward:

* Every coded task is allocated a secure, unique URL.
* Copy and share this URL with your participants.
* Participants access the task via the link, ensuring data collection is centralized within Cognition.

#### **4. Data Collection & Export**

With Cognition, data collection is real-time and intuitive:

* After task completion, participant data is automatically saved.
* Access and review data within your Cognition dashboard.
* Depending on your analysis tools, export data in various formats, including CSV, JSON, and SQL.

#### **5. Integrating External Libraries**

Customization and flexibility are paramount. If jsPsych doesn’t cover all your needs:

* Cognition allows the inclusion of external Javascript or CSS libraries.
* Simply upload your chosen libraries, which become accessible during experiment runs.

#### **6. Utilizing GitHub for Version Control**

For those with a preference for GitHub for version management:

* Cognition integrates seamlessly with GitHub Actions.
* This allows for the direct deployment of JsPsych experiments to the platform.

#### **Tips for New Users**

* **Start Simple:** If new to cognitive task design or jsPsych, begin with a basic task. As you become comfortable, expand and refine your experiments.
* **Utilize Templates:** Cognition provides pre-packaged templates. These can significantly reduce setup time, especially for standard cognitive tasks.
* **Data Management:** Regularly back up and export your data. While Cognition offers real-time data collection, having multiple data storage points is always prudent.
* **Stay Updated:** Cognition, like any platform, evolves. Stay updated with platform changes, added features, and any alterations in the jsPsych library.

In conclusion, Cognition offers a robust and user-friendly platform for online cognitive experiment design and deployment. With tools tailored for both beginners and experienced users, it streamlines the experimental process, allowing researchers to focus more on science and less on the IT side of things. Whether you're starting your first task or managing multiple complex experiments, Cognition is equipped to support your journey.


# Creating Your First Cognitive Task

Now that you're familiar with [Cognition's basics](/), let's dive deeper and create your first cognitive task. This guide will focus on developing a task from scratch using the online code editor, offering a hands-on introduction to the platform.

#### **1. Initiating a New Task**

Starting a new task is simple:

* From your [Cognition dashboard](https://www.cognition.run/tasks), click on "+New task".
* Enter a name for your task.
* Save your entry. This action will create a placeholder for your task.

#### **2. Accessing the Code Editor**

Your new task is empty at this point. Let’s bring it to life:

* Click on "Source code" to open the online code editor. This is where the magic happens.

#### **3. Crafting Your Task**

Instead of diving into code immediately, we'll utilize a tried-and-true example from the official JsPsych website:

* Navigate to the [Hello World Tutorial](https://www.jspsych.org/7.3/tutorials/hello-world/).
* Copy the following code:

```javascript
const jsPsych = initJsPsych();

const hello_trial = {
  type: jsPsychHtmlKeyboardResponse,
  stimulus: 'Hello world!'
}

jsPsych.run([hello_trial]);
```

* Return to the Cognition code editor and paste the code.

#### **4. Live Preview and Auto-save**

As you work in the code editor:

* The embedded live preview will dynamically update, providing real-time feedback on your task's appearance and functionality.
* Rest easy knowing the editor auto-saves your code, ensuring your progress is preserved.

#### **5. Enhancing Task Flexibility**

While our simple "Hello World" task doesn't require additional stimuli or third-party libraries, understanding how to add them is crucial for more complex experiments:

* Uploading stimuli or third-party libraries (both CSS and JS) can significantly enhance your task's functionality and aesthetics.
* For now, just remember this feature when you progress to more intricate tasks.

#### **6. Testing Your Task**

With your task coded, it’s time to see it in action:

* Return to your Cognition dashboard.
* Every task you create has a unique URL. Click on this URL to run your task.
* Complete the task as a participant would.

#### **7. Accessing Your Data**

After completing a run:

* The data generated will be stored on the platform.
* Access and download this data directly from your dashboard.

In summary, creating a cognitive task in Cognition is straightforward. With tools like the online code editor, live preview, and the ability to integrate complex stimuli and libraries, your experimental potential is vast. While this guide covered task creation from scratch, remember that [Cognition](https://www.cognition.run) also supports importing tasks from GitHub—a topic we'll delve into in future tutorials. Until then, enjoy experimenting!


# Sharing Your Experiments

Cognition’s primary aim is to simplify the experimental process. Once you've crafted your cognitive task, sharing it becomes a vital step. Here’s a guide on how to efficiently share and distribute your experiment to participants.

#### **1. Ensure Your Task is Ready**

Before diving into sharing methods, ensure that you've successfully created your cognitive task. If you haven't done so, refer to our previous section on "[Creating Your First Cognitive Task.](/creating-your-first-cognitive-task)"

#### **2. Understanding the Unique URL**

Each task you create in Cognition is automatically assigned a unique URL, which serves as the gateway to your experiment:

* The structure of this URL is as follows: `https://xxxxxxx.cognition.run`
* This URL acts as a direct link to your task, facilitating easy access for participants.

With the [Single-use Links](#id-6.-single-use-links-controlling-access) feature, you can further customize access to ensure each participant only completes the task once.

#### **3. Versatility of Access**

One of Cognition's strengths lies in its compatibility and accessibility:

* There's no need for participants to log in to run the task.
* The URL is platform agnostic. Whether participants are using desktop computers, tablets, or phones, they can access and complete the task.
* It's also browser-friendly, compatible with all major browsers.

#### **4. Security Assurances**

Data security and integrity are paramount:

* Every task URL is secured by the HTTPS protocol, ensuring data is transmitted securely.
* A valid Cognition SSL certificate backs these URLs, offering an additional layer of trust and security.

#### **5. Methods of Sharing Your Task**

With your secure and unique URL in hand, sharing becomes a breeze:

* **Direct Communication:** Share the URL directly through chat or email to selected participants.
* **Social Media:** Post the URL on platforms like Twitter, Facebook, or LinkedIn, expanding your reach.
* **Third-Party Research Tools:** If you're using platforms like MTurk or Prolific, you can embed or link your task URL there, accessing a broader participant pool.

#### **6.** Single-use Links: Controlling Access

The Single-use Links feature allows you to generate links that can be visited only once. This ensures that each participant completes the task only one time, providing more control over your data collection.

You can generate these links in two formats:

* **Sequential** URLs: Links follow a simple numeric order (e.g., ?link=1, ?link=2, etc.). This approach is useful when you need to track or organize participants in a structured way. However, since the links are in numeric order, they may be easier to guess. This format is ideal for experiments where the order of links matters.
* **Random** URLs: These links are randomly generated using unique identifiers (e.g., ?link=8f2r, ?link=q3mf). Random URLs add an extra layer of security, making it much harder for participants to predict or guess the link. This format is ideal for anonymous or sensitive experiments where security and confidentiality are important.


# Data Management and Download

Ensuring the security, integrity, and accessibility of experimental data is paramount in research. Cognition's platform prioritizes these aspects, providing a robust mechanism for data management and download. Here’s how Cognition handles your data:

#### **1. Real-time Data Collection**

As participants complete tasks, Cognition captures data in real-time, offering you up-to-the-minute insights into your experiments.

#### **2. Secure Data Transfer**

All data transmitted to Cognition's servers is sent via HTTPS, ensuring encrypted and secure communication that safeguards participant information.

#### **3. Data Encryption and Storage**

Upon arrival at our servers, data undergoes further encryption, adding an additional layer of protection. This encrypted data remains securely stored, inaccessible to external threats.

#### **4. Data Access Controls**

Data privacy is vital:

* Data isn't publicly accessible.
* Only after logging in can one download data. And even then, only the task's owner has the privilege to access and download its corresponding data. (For details on collaboration rights, refer to the "[Collaborators](/digging-deeper/task-collaborators)" section.)

#### **5. Jurisdictional Data Storage**

Cognition understands global research requirements:

* Users can specify in which jurisdiction their data is stored: North America, Europe, Japan, or Australia. If your jurisdiction isn’t listed, contact us for assistance.

#### **6. Customizable Data Download**

Flexibility is key when it comes to data retrieval:

* Choose to download individual runs, subsets of runs, or the complete set of task runs.
* Export formats include CSV, JSON, and SQL, catering to a range of analytical tools and preferences.
* Depending on your needs, download data as individual files or consolidated within a zip folder.
* Customize filenames by selecting which variables (columns) should be included, ensuring easy differentiation between data files from different runs.

#### **7. Offline Recovery**

In the event of connection issues where data transmission is interrupted:

* The system ensures data isn't lost. The next time the participant accesses the experiment, the system will automatically upload the previously untransmitted data.

In sum, Cognition’s approach to data management combines security, flexibility, and accessibility. With robust mechanisms for data capture, storage, and retrieval, researchers can focus on insights rather than infrastructure.


# Error debugging

Debugging is a crucial aspect of the experimental process. Catching and correcting errors before they impact participants is key to ensuring reliable results. [Cognition](https://www.cognition.run/) offers integrated tools to facilitate efficient debugging. Here's how you can harness these tools:

#### **1. Preemptive Error Detection**

Cognition's interface is designed to help users identify issues before their experiment goes live:

* Detecting errors during the design phase can save significant time and prevent faulty data collection.

#### **2. Precision in Code Editor**

One of the primary tools in your debugging arsenal is Cognition's code editor:

* It precisely pinpoints any exceptions in your code, highlighting the exact line and column where the exception has been thrown. This granular feedback assists in quickly locating and rectifying the problem.

#### **3. Real-time Exception Collection**

Even with meticulous pre-testing, there's a possibility that uncaught exceptions might arise during the actual execution of the experiment:

* Should this happen, Cognition proactively collects these unhandled exceptions from the participant's browser.
* These exceptions are then relayed to your dashboard, offering you a direct insight into any issues that occurred during a run.

#### **4. Marking Faulty Runs**

To ensure data integrity and assist in data analysis:

* Any run where an exception was thrown will be specifically marked as "With errors" on your dashboard. This labeling helps in easily identifying and potentially discarding problematic data sets.

#### **5. JsPsych Library & Debugging**

It's worth noting that while Cognition is tightly integrated with the JsPsych library, it doesn't serve as its official troubleshooting resource:

* If you encounter JsPsych-specific issues or need specialized guidance related to the library, the best resource is the official JsPsych website. You can find comprehensive documentation and support at [JsPsych's official site](https://jspsych.org/).

In conclusion, Cognition prioritizes a seamless debugging experience, arming researchers with the tools they need to ensure their experiments run smoothly. By offering detailed error feedback and real-time exception tracking, Cognition strives to make the experimental process as robust and efficient as possible.


# Digging deeper


# Informed consent

Informed consent is an ethical cornerstone of research. It ensures participants are fully aware of what they're committing to and that they participate voluntarily, understanding any risks or benefits. Cognition recognizes the importance of this step and has built-in features to seamlessly integrate informed consent into your tasks.

#### **1. Attaching Informed Consent**

As a researcher, you have the ability to:

* Attach an informed consent document directly to your tasks, ensuring participants encounter this crucial step right from the beginning.

#### **2. Mandatory Acceptance**

For tasks that have attached informed consents:

* Participants must explicitly accept the terms laid out in the informed consent before accessing the main task.
* This built-in measure ensures that every participant has at least been presented with and acknowledged the consent form.

#### **3. Printing Options**

To further enhance transparency and participant confidence:

* Cognition allows participants to print the informed consent document. This way, they can retain a physical copy for their records, if desired.

#### **4. Recording Consent Actions**

To keep an accurate record of participant interactions with the consent form:

* Cognition logs the exact time a participant accesses the consent form.
* Additionally, whether the participant accepts or rejects the informed consent is also recorded, ensuring you have a clear trail of participant decisions.

#### **5. Setting Up Informed Consent**

Making your informed consent accessible to participants is straightforward:

* Navigate to the Task's page.
* Here, you can set up the informed consent using markdown, a lightweight markup language that allows you to format text easily.

#### **6. Fallback URL for Rejections**

Research ethics require that participants have an easy way to exit a study if they choose not to participate:

* In Cognition, you can specify a fallback URL.
* If a participant opts to reject the informed consent, they will be automatically redirected to this URL, ensuring a smooth exit from the study.

In conclusion, Cognition’s approach to informed consent emphasizes both participant rights and research ethics. The platform makes it easy to integrate, present, and track informed consent, ensuring that every step of the research process aligns with best practices and ethical considerations.


# Task Collaborators

Collaboration is often essential in research, allowing for diverse expertise and multiple sets of eyes on a project. Recognizing this, [Cognition](https://www.cognition.run/) offers comprehensive collaboration tools. Here's how you can seamlessly integrate collaborators into your tasks:

#### **1. Adding Collaborators to a Task**

A single task in Cognition can benefit from the insights of multiple collaborators. Here's how to integrate them:

* Tasks you're collaborating on will be visible on your personal dashboard, making access straightforward.
* To invite a new collaborator, all you need to do is provide their email address. Note, however, that the individual must already be a registered user of Cognition.run.

#### **2. Levels of Collaboration**

Understanding that not all collaborators require the same access, Cognition offers tiered levels of collaboration:

* **Viewers:**
  * Their access is the most limited, primarily designed for those who need insight into the task but shouldn't make modifications.
  * They can share the task link, providing others with a view into the task, but cannot make edits or access data.
* **Editors:**
  * A step above viewers, editors can delve deeper into task modifications.
  * They possess the ability to both share the task link and edit the task as required.
  * However, data privacy is preserved, as they cannot download the collected data.
* **Owners:**
  * The most comprehensive level of access is reserved for owners.
  * Like editors, they can share and edit the task, but they also have the ability to download the collected data.
  * Additionally, they can expand the collaboration circle by inviting new collaborators, ensuring the right people have access at all times.

#### **3. Modifying Collaborator Access**

It's common in research for roles to evolve. As your project progresses:

* Consider revisiting the access levels of your collaborators. Perhaps a viewer now needs editing capabilities, or an editor should be elevated to an owner.
* Cognition makes these adjustments simple, ensuring that as your research needs shift, your collaborators' access can shift with them.

In summary, Cognition’s collaboration features are designed to mirror the dynamic nature of research. Whether you're working with a small team or a large cross-disciplinary group, Cognition ensures everyone has the right level of access to contribute effectively to the task at hand.


# Inter experiment conditions

When designing experiments, especially in psychological and behavioral research, between-group designs are commonplace. These designs involve comparing two or more groups, with each group experiencing a different condition. [Cognition](https://www.cognition.run/) has integrated tools to efficiently manage these inter-experiment conditions. Let's delve into how you can utilize this feature:

#### **1. The Essence of Between-Group Study Design**

In between-group (or between-groups) designs, different participants are assigned to different conditions, ensuring that each group experiences only one of the conditions.

#### **2. Automatic Participant Assignment**

Cognition streamlines the condition assignment process by:

* Automatically allocating participants to different conditions.
* If you specify multiple conditions, Cognition will ensure an even distribution of participants across these conditions. This balance ensures unbiased results and easier statistical analysis.

#### **3. Accessing Assigned Condition in Runtime**

Once a participant is assigned to a condition, this information is made available during the experiment runtime via the variable `CONDITION`.

#### **4. Practical Application**

Let's explore a practical code example to understand how `CONDITION` can be harnessed:

```javascript
var test_stimuli = [
    { stimulus: "img/blue.png", correct_response: CONDITION == 2 ? 'f' : 'j' },
    { stimulus: "img/orange.png", correct_response: CONDITION == 2 ? 'j' : 'f' }
];
```

In this scenario:

* If a participant has been assigned to Condition 2, their correct responses will be 'f' for the blue image and 'j' for the orange image.
* For participants in any other condition, the correct responses are reversed.

#### **5. Testing Specific Conditions**

While editing your task and using the live preview function:

* Cognition provides an option titled "Set condition."
* This tool allows you to simulate a specific condition, ensuring you can test the task as if you were a participant assigned to that condition.

**6. Set Specific Condition Using URL Query Parameters**

In addition to the automatic condition assignment feature, Cognition offers flexibility in allowing researchers to set specific conditions using URL query parameters. By appending the query parameter `condition` to the experiment URL, researchers can bypass the auto-balancing algorithm and ensure that a participant sees a specific version of the experiment.

For example, if you append `?condition=2` to the experiment URL, the participant will be assigned to Condition 2 regardless of the auto-balancing logic. This feature is particularly useful for researchers who wish to control the version seen by specific participants, allowing for more targeted experimentation.

**7. Pros of Using Conditions vs. Creating Multiple Tasks**

When designing experiments with between-group study designs, researchers often face the decision of whether to use conditions within a single task or create multiple tasks. Each approach has its own set of advantages and disadvantages:

**Pros of Using Conditions:**

* **Single Unique URL:** With conditions, researchers only need to manage a single unique URL for the experiment, simplifying participant recruitment and sharing.
* **Auto-Balancing:** Cognition's auto-balancing system ensures an even distribution of participants across conditions, leading to more reliable and unbiased results.
* **Easy Maintenance:** Managing a single task with conditions is more straightforward and requires less maintenance compared to managing multiple tasks.

In conclusion, the inter-experiment conditions feature in Cognition greatly simplifies the process of managing and implementing between-group study designs. Whether you're comparing two conditions or several, Cognition ensures a balanced and efficient distribution of participants, all while giving you the tools to easily craft and test condition-specific task elements.


# Using Query Params

Query parameters play a pivotal role in making web applications, including online experiments, more versatile and customizable. Let's unpack how Cognition leverages query parameters to enhance the user experience and expand experimental possibilities.

#### **1. What are Query Parameters?**

At a basic level, query parameters are specific sets of keys and values appended to a URL. They start after a question mark (`?`) and are often separated by ampersands (`&`). For instance, in the URL `https://example.com?subject=123&group=A`, `subject` and `group` are query parameters.

#### **2. Accessing Query Parameters in Code**

JsPsych, integrated within Cognition, provides a simple function to access these parameters:

```javascript
// Given the URL: https://abcdfge.cognition.run?subject=1234&condition=test

console.log(jsPsych.data.getURLVariable('subject')) // Outputs: "1234"
console.log(jsPsych.data.getURLVariable('condition')) // Outputs: "test"
```

By employing the `jsPsych.data.getURLVariable` function, you can directly tap into the query parameters' values and use them in your experimental logic.

#### **3. Integrating with Third-party Applications**

By utilizing query parameters, Cognition can:

* Seamlessly integrate with third-party applications or platforms.
* Allow external platforms to pass necessary information to the experiment, enhancing configurability.

#### **4. Customizing Experimental Logic**

Query parameters offer a dynamic way to adjust experimental logic:

* Depending on the query parameters passed, your experiment can adapt its behavior.
* This adaptability is crucial for tailoring tasks to specific groups or even individual participants.

```javascript
// Given the URL: https://abcdfge.cognition.run?link=1

if (jsPsych.data.getURLVariable('link') == 1) {
    timeline.push(trial_1);    
}
```

#### **5. Practical Applications**

Query parameters offer numerous practical benefits:

* **Subject Identification:** Differentiate participants by assigning unique subject IDs via query parameters.
* **Custom Redirects:** Direct participants to different end pages based on specific query parameters.
* **Participant Rewards:** By generating unique URLs for each participant using query parameters, you can track and reward those who complete the experiment.

#### **6. Data Collection and Analysis**

In addition to enhancing real-time experiment dynamics:

* Cognition ensures that query parameters are appended to the collected data. This inclusion is immensely beneficial during data analysis, allowing researchers to categorize, filter, or analyze based on specific parameters.

#### **7. Development and Testing**

As you develop your experiment using Cognition's online code editor:

* You can simulate the presence of query parameters by clicking on the "Add url params" option. This feature ensures you can test and refine your task's behavior based on various query parameter configurations.

To wrap up, query parameters are a robust tool in Cognition's toolkit, enabling more dynamic, adaptable, and versatile experiments. Whether you're looking to customize tasks, integrate third-party platforms, or simply enhance data analysis, query parameters stand ready to deliver.


# Offline Recovery

In the world of online cognitive experiments, ensuring data integrity is paramount. Researchers rely on accurate and complete data to draw meaningful insights and conclusions from their studies. However, in an environment where internet connectivity can be unpredictable, the risk of data loss due to connection disruptions is a concern. This is where offline recovery comes into play, offering a solution to mitigate the impact of internet downtime on data collection.

**What is Offline Recovery?**

Offline recovery is a feature designed to safeguard data integrity in cognitive experiments, even in situations where internet connectivity is disrupted. There are two main scenarios in which offline recovery comes into play:

1. **Recovery of Data after Connection Loss:** If a participant loses internet connection during the experiment and later regains it, offline recovery ensures that the collected data is sent to the server once connectivity is restored.
2. **Recovery of Data after Participant Leaves the Website:** In the event of a connection loss where the participant leaves the experiment website, offline recovery ensures that the stored data is sent to the server the next time the participant visits the experiment URL.

**How Does Offline Recovery Work?**

Offline recovery operates on a simple yet effective principle. At every trial of the experiment, the collected data is persisted in the participant's browser local storage. If the connection is lost and the data cannot be immediately sent to the server, it remains stored securely in the browser.

When the participant revisits the experiment URL, the stored data is automatically sent to the server, ensuring that no data is lost due to connection disruptions. Once the data is successfully transmitted, it is removed from the local storage, maintaining the participant's privacy and data security.

**Can Researchers Access Offline Data?**

One common question researchers may have is whether they can access the offline data stored in the participant's browser local storage or force the browser to send it back. The answer is no. Offline data is securely stored in the participant's browser local storage and is not accessible by researchers. Researchers can only prompt the data to be sent back by instructing participants to revisit the experiment's link.

In summary, offline recovery is a valuable feature that enhances the reliability and robustness of data collection in online cognitive experiments. By safeguarding against data loss due to connection disruptions, offline recovery ensures that researchers can trust the integrity of their data, ultimately leading to more accurate and meaningful research outcomes.


# GitHub integration

Using GitHub to manage your experiment's code can be immensely beneficial, providing version control, collaboration features, and much more. With Cognition's GitHub integration, you can seamlessly deploy your JsPsych experiments directly from your repository. Here's how you can set it up:

#### **1. Generate a Personal Access Token**

* Start by creating a new Personal Access Token on GitHub. This token will authenticate your requests.
* Once generated, make sure to copy this secret token for future use.

#### **2. Add the Token to Repository Secrets**

* Navigate to the main page of your repository on GitHub.
* Click on "Settings" right under your repository name.
* In the sidebar, under the "Security" section, select "Secrets" followed by "Actions".
* Click on "New repository secret".
* For the name, input `PERSONAL_ACCESS_TOKEN`.
* Paste the previously copied secret token in the value field.
* Finally, click "Add secret" to save it.

#### **3. Setting up the Workflow Directory**

* Check if your repository has a `.github/workflows` directory. If not, create one.
* Inside the `.github/workflows` directory, create a file named `cognition-github-actions.yml`.

#### **4. Crafting the Workflow File**

* Now, copy and paste the following YAML content into the `cognition-github-actions.yml` file:

```yaml
on: [push]

jobs:
  cognition-deploy:
    runs-on: ubuntu-latest
    name: Deploy experiment to Cognition
    steps:
      - uses: actions/checkout@v3
      - uses: javidalpe/cognition-deploy-action@v1.2.0
        id: deploy
        with:
          personal-access-token: ${{secrets.PERSONAL_ACCESS_TOKEN}}
      - run: echo "The public link to the task is ${{ steps.deploy.outputs.link }}"
```

#### **5. Triggering the Workflow**

* Once you've added and committed the workflow file to your repository, every subsequent push to the repository will trigger this workflow.
* When triggered, this workflow will automatically deploy your experiment to Cognition.

#### **6. Deployment Confirmation**

* After each deployment, the workflow will output the public link to the deployed task in the GitHub Actions logs. You can use this link to directly access and share your task.\ <br>

**Frequently Asked Question:**

**How does Cognition determine the location of the JavaScript code?**

Cognition will look for an index.html file. If this file exists, Cognition will use the JavaScript code inside the file. However, if there is an index.js file present, the index.html will be ignored, and the content of the index.js file will be saved as the source code. Any other .js files will be stored and served as external libraries.

In conclusion, Cognition's GitHub integration offers a smooth and efficient way to manage and deploy your JsPsych experiments. This streamlined approach ensures that the latest version of your experiment is always available on Cognition, facilitating continuous development and deployment.

<br>


# Live Monitoring

Live Monitoring is an advanced feature available exclusively with the Team Plan subscription on Cognition. This feature empowers researchers and teams to conduct real-time monitoring of participants during cognitive tasks, enhancing collaboration and data collection efficiency.

**Key Features:**

1. **Real-time Participant Screen Viewing:**
   * With Live Monitoring, researchers can observe participants' screens in real time as they interact with the cognitive task. This provides valuable insights into participant behavior and task engagement.
2. **Bidirectional Communication:**
   * Live Monitoring facilitates bidirectional communication between researchers and participants using a microphone. Researchers can provide instructions, ask questions, or offer assistance in real time, fostering a more interactive research environment.
3. **Real-time Data Collection Insights:**
   * Researchers have access to real-time data collection insights during Live Monitoring sessions. This allows for immediate analysis of participant responses and performance, enabling researchers to make informed decisions on the fly.

**Enabling Live Monitoring:**

* To enable Live Monitoring for a specific task, simply enable the "Requires monitoring" option during the creation of the task. Once the task is created, this property cannot be changed, ensuring consistency throughout the monitoring process.

**Important Considerations:**

* **Team Plan Requirement:** Live Monitoring is only available with the Team Plan subscription on Cognition. Each registered user receives 5 monitoring sessions for free.
* **Experimental Feature:** Please note that Live Monitoring is an experimental feature and may undergo further development and refinement. Feedback from users is highly encouraged to help improve the feature.
* **Not Available on Mobile Phones:** Live Monitoring is not currently available on mobile phones. It is recommended to use a desktop or laptop computer for conducting monitoring sessions.

**Contact Us:**

* If you encounter any issues or have feedback regarding Live Monitoring, please don't hesitate to contact our support team. We are committed to providing the best possible experience for our users and welcome your input.


# MCP Server

### What is it

The Cognition MCP server is a remote [Model Context Protocol](https://modelcontextprotocol.io/) server that connects AI assistants — such as Claude, ChatGPT, Cursor, and others — to your cognition.run account. It allows you to manage experiments, monitor participant sessions, deploy code, and retrieve results directly from a conversational AI interface, without leaving your workflow.

### What is it for

The server is designed for researchers who use cognition.run to host jsPsych-based behavioral experiments. Instead of switching between the cognition.run dashboard and your AI assistant, you can:

* Create and configure experiments by describing them in natural language.
* Deploy and update jsPsych source code to a live experiment URL.
* Control data collection: open recruitment, pause it, or set automatic stop rules.
* Monitor participant sessions and review completion status.
* Retrieve trial-level behavioral data for analysis.
* Manage collaborator access and informed consent forms.
* Generate and manage single-use participant links.

The MCP server acts as a hosting and management control plane. It does not write your experiment code for you — your AI assistant does that. The server deploys, hosts, and manages what the assistant produces.

### How it works

1. You connect your cognition.run account to an MCP-compatible AI client (see Authentication below).
2. You describe what you want in plain language — for example, "create a new experiment called Stroop Pilot" or "show me how many participants have completed my study."
3. The AI client translates your request into one or more MCP tool calls to the Cognition server.
4. The server executes the operation against your cognition.run account and returns the result.
5. The AI client presents the result in the conversation and can take follow-up actions based on it.

All operations are scoped to your authenticated account. The server only accesses projects you own or that have been shared with you.

### Authentication

The Cognition MCP server requires OAuth 2.0 authentication. When you connect for the first time, your AI client will open a browser window where you log in with your existing cognition.run credentials and authorize the connection. No API keys or configuration files are required.

#### Connecting from Claude (claude.ai or Claude Desktop)

1. Open Settings and go to Connectors.
2. Find "Cognition" in the directory, or add a custom connector with the URL: `https://www.cognition.run/mcp`
3. Click Connect. A browser window opens with the cognition.run login page.
4. Log in and authorize the connection.
5. The connector is now available in your conversations.

#### Connecting from ChatGPT

1. Go to Settings, then Apps & Connectors, then Advanced.
2. Enable Developer Mode (requires Pro, Business, Enterprise, or Edu plan).
3. Create a new connector with the URL: `https://www.cognition.run/mcp`
4. Complete the OAuth flow in the browser when prompted.

#### Connecting from Claude Code

1. Run: `claude mcp add cognition --transport http https://www.cognition.run/mcp`
2. Complete the OAuth flow when prompted in your browser.

#### Revoking access

You can revoke the MCP connection at any time from your cognition.run account settings under "Connected Applications." Revoking access immediately invalidates all tokens. You will need to re-authorize if you want to reconnect.

### Available tools

#### Experiments

| Tool          | Description                                                                                                                                    | Access      |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | ----------- |
| `list-tasks`  | List all your experiments, including shared ones.                                                                                              | Read-only   |
| `create-task` | Create a new experiment. Accepts name, language, number of between-subject conditions, IP storage preference, and email notification settings. | Write       |
| `get-task`    | View an experiment's configuration, participant count, and collection status.                                                                  | Read-only   |
| `update-task` | Modify experiment settings: name, language, conditions, jsPsych library version, IP storage, email notifications, and PHI mode.                | Write       |
| `delete-task` | Permanently delete an experiment and all its collected data.                                                                                   | Destructive |

#### Source code

| Tool                 | Description                                                                      | Access    |
| -------------------- | -------------------------------------------------------------------------------- | --------- |
| `get-source-code`    | Read the jsPsych code that defines the experiment's trial structure and stimuli. | Read-only |
| `update-source-code` | Deploy new or updated jsPsych source code to the experiment.                     | Write     |

#### Data collection

| Tool                     | Description                                                                                                                | Access    |
| ------------------------ | -------------------------------------------------------------------------------------------------------------------------- | --------- |
| `get-data-collection`    | Check whether an experiment is open for participants and view stop rules.                                                  | Read-only |
| `update-data-collection` | Open or close recruitment. Supports immediate stop, stop at a specific date, or stop after a target number of completions. | Write     |

#### Participant sessions

| Tool           | Description                                                                                                                    | Access      |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------ | ----------- |
| `list-runs`    | Browse participant sessions with completion status and timestamps. Supports pagination.                                        | Read-only   |
| `get-run`      | Inspect a single session: status, consent, errors, and metadata.                                                               | Read-only   |
| `get-run-data` | Retrieve trial-level behavioral data from a participant session. Subject to PHI mode restrictions (see Privacy section below). | Read-only   |
| `delete-run`   | Permanently delete a session and its data.                                                                                     | Destructive |

#### Participant links

| Tool               | Description                                                                            | Access      |
| ------------------ | -------------------------------------------------------------------------------------- | ----------- |
| `list-links`       | Browse single-use participant links and their consumption status. Supports pagination. | Read-only   |
| `create-links`     | Generate 1 to 500 single-use links with sequential or random token codes.              | Write       |
| `delete-link`      | Delete a single participant link.                                                      | Destructive |
| `delete-all-links` | Delete all participant links for an experiment.                                        | Destructive |

#### Informed consent

| Tool             | Description                                                                                                                                           | Access      |
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- |
| `get-consent`    | Read the consent form shown to participants before the experiment.                                                                                    | Read-only   |
| `update-consent` | Write or update the consent form. Accepts plain text or Markdown (minimum 50 characters). Optionally set a redirect URL for participants who decline. | Write       |
| `remove-consent` | Remove the consent requirement from the experiment.                                                                                                   | Destructive |

#### Collaborators

| Tool                       | Description                                               | Access      |
| -------------------------- | --------------------------------------------------------- | ----------- |
| `list-collaborators`       | See who has access to an experiment and their roles.      | Read-only   |
| `add-collaborator`         | Invite a researcher by email as viewer, editor, or owner. | Write       |
| `update-collaborator-role` | Change a collaborator's role.                             | Write       |
| `remove-collaborator`      | Revoke a collaborator's access.                           | Destructive |

### Usage examples

#### Example 1: Create and deploy an experiment

**Prompt:** "Create a new experiment called 'Stroop Pilot', set the language to English, and deploy a basic Stroop task with 20 congruent and 20 incongruent trials."

What happens: The assistant calls `create-task` with the name and language, then generates jsPsych code for the Stroop task, and calls `update-source-code` to deploy it. The experiment is immediately accessible at its public URL.

#### Example 2: Monitor recruitment progress

**Prompt:** "How many participants have completed my Flanker Task study? Set it to stop automatically at 50 completions."

What happens: The assistant calls `get-task` to retrieve the current participant count, then calls `update-data-collection` with mode `stop-at-runs` and a target of 50.

#### Example 3: Retrieve and analyze data

**Prompt:** "Get the data from participant 12 in my Stroop Pilot and calculate mean reaction times by condition."

What happens: The assistant calls `get-run-data` for the specified session, receives the trial-level data, and writes an analysis script to compute the summary statistics.

### Privacy and Protected Health Information (HIPAA)

Cognition.run is used by researchers who may collect sensitive health-related data from experiment participants. The MCP server includes safeguards to prevent unintended exposure of Protected Health Information (PHI) through AI assistant connections.

#### PHI mode

Every experiment has a `phi_mode` setting with three states:

**Not declared (default).** When the MCP server receives a request to access participant data for a project that has not declared its PHI status, it returns an error prompting the researcher to classify the project. The AI assistant will ask you whether the experiment collects health-related information linked to identifiable participants. Your declaration is recorded with a timestamp.

**PHI mode off (`false`).** The researcher has declared that the experiment does not collect PHI. Participant data is accessible through the MCP server normally. This is appropriate for most cognitive psychology experiments that use anonymous participant codes and collect only behavioral measures such as reaction times and accuracy.

**PHI mode on (`true`).** The researcher has declared that the experiment collects PHI. Participant data is not accessible through the MCP server — neither as raw data nor as a downloadable URL. The researcher must download data directly through their authenticated browser session on cognition.run. The AI assistant can still access the data schema (column names, types, and aggregate statistics) to help write analysis scripts, but never the raw values.

PHI mode can be set via `update-task` with the `phi_mode` parameter, or through the cognition.run dashboard. Once set to `true`, it can only be changed back to `false` from the dashboard — not via MCP. This prevents accidental or automated declassification.

#### Why this matters

When you connect an AI assistant via MCP, data returned by the server enters the assistant provider's infrastructure (Anthropic, OpenAI, etc.). Cognition.run does not have Business Associate Agreements (BAAs) with these providers. Sending PHI through an MCP connection is not HIPAA-compliant. The `phi_mode` safeguard exists to prevent this from happening inadvertently.

#### Researcher responsibility

The researcher is solely responsible for accurately classifying whether an experiment contains PHI. Cognition.run provides the declaration mechanism as a reasonable safeguard but does not independently verify the nature of collected data.

For the full privacy policy, see [cognition.run/privacy](https://www.cognition.run/privacy). For terms of service, see [cognition.run/terms](https://www.cognition.run/terms).

### Troubleshooting

**OAuth flow does not complete.** Make sure you are using a supported AI client (Claude, ChatGPT with Developer Mode, Claude Code, or another MCP-compatible client). Check that your browser allows pop-ups from your AI client's domain. If the flow times out, try disconnecting and reconnecting.

**Tool calls return "unauthorized" errors.** Your token may have expired or been revoked. Disconnect the connector in your AI client's settings and reconnect to obtain a fresh token.

**"PHI mode not declared" error when accessing data.** The experiment has not been classified yet. Tell your AI assistant whether the experiment collects health information linked to identifiable participants. The assistant will set the appropriate mode and retry.

**Data access blocked on a PHI-protected project.** This is working as intended. Download the data directly from cognition.run in your browser. You can ask the AI assistant to write analysis scripts based on the data schema without exposing the raw values.

**Tool call returns a large error or no data.** Check that the experiment ID and run ID are correct. Use `list-tasks` and `list-runs` to verify available resources. If the problem persists, contact support.

**Experiment code fails after deployment.** Use `get-source-code` to inspect what was deployed. The MCP server deploys code as-is; it does not validate jsPsych syntax. Test your experiment in a browser after deployment by visiting its public URL.

### Support

For technical issues, account questions, or security concerns:

**Email:** <support@cognition.run>

**Documentation:** [docs.cognition.run](https://docs.cognition.run/)

**Security vulnerabilities:** If you discover a security issue, please report it to <security@cognition.run>. We will acknowledge receipt within 48 hours.


